SlideShare a Scribd company logo
Controllers
Jill Gundersen
CakePHP Request
 More Detailed Version of the CakePHP Request
Routes
 Parse the Request URL


Extracts parameters



e.g. controller, action, additional values passed in the URL.
http://catalog/items/view/12

 The Request URL Parameters are then Mapped to a Controller Action


A specific action in a specific controller class.




items controller
view action (function)
12 value to use with the database
Controller
 The Controller Interacts With the Model




Controller calls on the model if there is a need to gain access to the
application’s data.
Model interacts with the database and returns data back to the controller.

 The Controller then Interacts With the View




Controller can use the data from the model and manipulate it for the benefit
of the view
After the controller has the prepared the data, the controller passes the data
off to the view
A Tasty Example

Ingredients

Order

Enjoy!

Chef

Placed on Plate
A Tasty Example

Model

Route

End User

Controller

View
What’s In Store?
 Continue Development of Our Catalog Web Site


DVDs, Books, CDs, etc.

 Add to the Controller


Add Actions (functions) to the ItemsController we made in “Getting Started”
module





Display a List all the Items
Create and Delete an Item
Update and Display a Detailed View of an Item
Search the Items
Setting Variables
 Passing Variables to the View


The set() method is used to pass variables to the view.


First Parameter




Second parameter




Provide a name
Provide the value or data

Example


Controller




$this->set(‘pizza’, ‘pepperoni’);

View


Their favorite pizza is <? echo $pizza; ?>.
Query the Database
 Accessing the Database Model in Controller


Access the Model via $this->ModelName


Example




$this->Item

Retrieve Data from the Model Using find() Method


Example
Query the Database
 find() Parameters


First Parameter:




all / first / count / neighbors / list / threaded

Second Parameter:


Array of Data




Example

conditions / fields / joins / limit / offset / order / page / group / callbacks
Single Query
 Query Based on ID



findById()
Example


$this->ModelName->findById($id);
Throw an Exception
 CakePHP Has Many Error Exceptions


http://book.cakephp.org/2.0/en/development/exceptions.html

 Handling Errors



throw new NotFoundException
Example


throw new NotFoundException(__(“Your item was not found”));
Form Data
 CakeRequest





Default request object in CakePHP. Passed by reference to the various layers
of an application.
Assigned to $this->request
Example



Holds all the data from the form (modified and unmodified)
$this->request->data

 Check How the Data Was Sent



is()
Takes One Parameter




post / get / put / delete / head / options / ajax / ssl / flash / mobile

Example


$this->request->is(‘post’);
Create & Save
 Adding a New Item Into a Database





create()
Resets the model state for saving new information. Clears out the model $id
value
Example


$this->ModelName->create();

 Saving the Data



save()
Parameters






1st : Array-formatted data to be saved.
2nd : Allows you to side step validation (bool) – optional
3rd : Supply a list of model fields to be saved. – optional

Example


$this->ModelName->save($this->request->data);
Redirect
 Sending a User to a Different Page




Sometimes it is necessary
redirect()
Parameters:






Example






String action (if in same controller)
Array controller & action
Relative path
$this->redirect(‘index’);
$this->redirect(array( ‘controller’ => ‘Items’, ‘action’ => ‘index’));
$this->redirect(‘/Items/thanks’);

More Redirect Examples


http://book.cakephp.org/2.0/en/controllers.html#flow-control
Saving An Existing Entry
 Saving an Item




Use the same save method that we utilized in the add() action, but we
eliminate the need for the create() method to be called before hand.
Example




$this->ModelName->save($this->request->data);

Override the ‘id’ in our model


Example


$this->ModelName->id = $id;
Populating the Form
 Editing a Form




When you edit an item you need to populate the form with the content of
the item you are editing.
Example



$item = $this>ModelName->findById($id);
$this->request->data = $item;
Set and Display Message
 Session Component


CakePHP provides a messaging system with the session component

 Adding the Session Component to Your Controller


public $components = array('Session');

 Using the Session Component


Example




$this->Session

Access the Method



setFlash()
Parameter




String message you want to display

Example


$this->Session->setFlash(__(“Your record was saved.”));
Does it Exist?
 Previous Determination



$data = $this->ModelName->findById($id)
if(!$data)


Throw Exception

 Check to See if an Item Exists in the Database




exists()
Returns Bool Value
Parameters




$id (optional)

Examples





$this->ModelName->exists($id);
$this->ModelName->id = $id;
$this->ModelName->exists()
Delete Item
 Deleting an Item in the Database




delete()
Returns Bool Value
Parameters




$id (optional)

Examples





$this->ModelName->delete($id);
$this->ModelName->id = $id;
$this->ModelName->delete()
Render Method
 Normal Behavior


Calls the view template of the same name as the action




index() => index.ctp

Called automatically at the end of the action in the controller

 Override




Reuse, Plugins, Elements, etc.
render()
Parameter




Name of the template you would like to use

Example



$this->render(‘index’);
$this->render(‘/Cakes/index’);


app/View/Cakes/index
Summary
 A Review of the MVC Framework


Better understanding of the role of the controller

 Added Actions (Functions) to Our Items Controller


Basic CRUD actions







Create
Read
Update
Delete

Search

More Related Content

PDF
3 introduction-php-mvc-cakephp-m3-getting-started-slides
PDF
6 introduction-php-mvc-cakephp-m6-views-slides
PDF
2 introduction-php-mvc-cakephp-m2-installation-slides
PDF
CakePHP: An Introduction
PPTX
PPTX
Django Girls Tutorial
KEY
LvivPy - Flask in details
PDF
Basic Crud In Django
3 introduction-php-mvc-cakephp-m3-getting-started-slides
6 introduction-php-mvc-cakephp-m6-views-slides
2 introduction-php-mvc-cakephp-m2-installation-slides
CakePHP: An Introduction
Django Girls Tutorial
LvivPy - Flask in details
Basic Crud In Django

What's hot (20)

PDF
Build website in_django
PDF
Django
PDF
CakePHP
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
KEY
CakePHP 2.0 - It'll rock your world
PPTX
Introduction to windows power shell in sharepoint 2010
ODP
Django for Beginners
PDF
Build and deploy Python Django project
PPTX
PPTX
RESTful Web Development with CakePHP
PDF
PloneNG: What's new in Plone 4.2, 4.3, and beyond
PPTX
Web development with django - Basics Presentation
PDF
Building a Dynamic Website Using Django
PDF
Introduction to django
KEY
Php Unit With Zend Framework Zendcon09
PDF
Quick flask an intro to flask
DOCX
Spring review_for Semester II of Year 4
PPTX
Zend framework
PPT
WordPress Plugin Basics
PDF
The Django Web Application Framework
Build website in_django
Django
CakePHP
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
CakePHP 2.0 - It'll rock your world
Introduction to windows power shell in sharepoint 2010
Django for Beginners
Build and deploy Python Django project
RESTful Web Development with CakePHP
PloneNG: What's new in Plone 4.2, 4.3, and beyond
Web development with django - Basics Presentation
Building a Dynamic Website Using Django
Introduction to django
Php Unit With Zend Framework Zendcon09
Quick flask an intro to flask
Spring review_for Semester II of Year 4
Zend framework
WordPress Plugin Basics
The Django Web Application Framework
Ad

Viewers also liked (20)

PDF
2. owin and katana aspdotnet-mvc5-slides
PDF
2 seo-fundamentals-in depth keyword research (part 2)-slides
PDF
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
PDF
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
PDF
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
PDF
7. signal r aspdotnet-mvc5-slides
PDF
8. web developer tools and visual studio 2013 aspdotnet-mvc5-slides
PPT
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
PDF
6. entity framework 6 aspdotnet-mvc5-slides
PDF
Introducing wcf-slides
PDF
5. web api 2 aspdotnet-mvc5-slides
PDF
Pd fbuoi7 8--tongquanseo-mastercode.vn
PDF
Pdf bai 7 làm việc với truy vấn nâng cao-slide 07-quan tri csdl voi access-ma...
PDF
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
PDF
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
PDF
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
PPTX
THUYẾT TRÌNH VỀ TIẾN TRÌNH LẮNG NGHE
PPT
ERD - Database Design
PDF
Odata consuming-services-slides
2. owin and katana aspdotnet-mvc5-slides
2 seo-fundamentals-in depth keyword research (part 2)-slides
Pdf buoi3 4-link-building-tran-ngoc-chinh-mastercode.vn
Pd fbuoi1 giới thiệu seo tools cơ bản-seo manager + seo guy-mastercode.vn
Pd fbuoi5 6-ảnh hưởng của social media tới kết quả seo-mastercode.vn
7. signal r aspdotnet-mvc5-slides
8. web developer tools and visual studio 2013 aspdotnet-mvc5-slides
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
6. entity framework 6 aspdotnet-mvc5-slides
Introducing wcf-slides
5. web api 2 aspdotnet-mvc5-slides
Pd fbuoi7 8--tongquanseo-mastercode.vn
Pdf bai 7 làm việc với truy vấn nâng cao-slide 07-quan tri csdl voi access-ma...
Pdfbài 7 máy tính xác tay và máy in bảo trì sự cố máy tính-mastercode.vn
Pdfbài 6 bảo trì máy tính bảo trì sự cố máy tính-mastercode.vn
Pd fbuoi3 4-kỹ thuật xây dựng back link-mastercode.vn
THUYẾT TRÌNH VỀ TIẾN TRÌNH LẮNG NGHE
ERD - Database Design
Odata consuming-services-slides
Ad

Similar to 4 introduction-php-mvc-cakephp-m4-controllers-slides (20)

PPT
Synapseindia reviews sharing intro cakephp
DOC
How to migrate Cakephp 1.x to 2.x
PPT
Top 50 Interview Questions and Answers in CakePHP
PDF
Ch ch-changes cake php2
KEY
CakePHP 2.0 - PHP Matsuri 2011
PPTX
Ei cakephp
PPTX
Cakeph pppt
PPT
Lecture n
PPT
Language literacy
PPTX
PDF
Introduction to CakePHP
PDF
Introduction to CakePHP
ODP
Get going with CakePHP Framework at gnuNify 2010
PPT
Intro to CakePHP 1.3
PDF
PPTX
cakephp UDUYKTHA (1)
PDF
CakePHP 3.0: Embracing the future
PDF
An Introduction to CakePHP
ODP
Don't Code, Bake. An introduction to CakePHP ~PHP Hampshire Oct 2014
PDF
Cakephp Interview Questions
Synapseindia reviews sharing intro cakephp
How to migrate Cakephp 1.x to 2.x
Top 50 Interview Questions and Answers in CakePHP
Ch ch-changes cake php2
CakePHP 2.0 - PHP Matsuri 2011
Ei cakephp
Cakeph pppt
Lecture n
Language literacy
Introduction to CakePHP
Introduction to CakePHP
Get going with CakePHP Framework at gnuNify 2010
Intro to CakePHP 1.3
cakephp UDUYKTHA (1)
CakePHP 3.0: Embracing the future
An Introduction to CakePHP
Don't Code, Bake. An introduction to CakePHP ~PHP Hampshire Oct 2014
Cakephp Interview Questions

More from MasterCode.vn (20)

PDF
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
PDF
Why apps-succeed-wpr-mastercode.vn
PDF
Dzone performancemonitoring2016-mastercode.vn
PDF
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
PDF
Nghiên cứu về khách hàng mastercode.vn
PDF
Lập trình sáng tạo creative computing textbook mastercode.vn
PDF
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
PDF
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
PDF
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
PDF
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
PDF
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
PDF
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
PDF
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
PDF
Pdf bai 6 làm việc với truy vấn cơ bản-slide 06-quan tri csdl voi access-mast...
PDF
Pdf bai 5 làm việc với báo cáo nâng cao-slide 05-quan tri csdl voi access-mas...
PDF
Pdf bai 4 làm việc với báo cáo cơ bản-slide 04-quan tri csdl voi access-maste...
PDF
Pdf bai 3 làm việc với biểu mẫu nâng cao-slide 03-quan tri csdl voi access-ma...
PDF
Pdf bai 2 làm việc với biểu mẫu cơ bản-slide 02-quan tri csdl voi access-mast...
PDF
Pdf bai 1 tổng quan về ms access-quan tri csdl voi access-mastercode.vn
PDF
Pdf tim hieuc#vaungdung-mastercode.vn
Pd ftai lieu-tieng-anh-cho-nguoi-moi-bat-dau-mastercode.vn
Why apps-succeed-wpr-mastercode.vn
Dzone performancemonitoring2016-mastercode.vn
Google công bố thông tin lịch xu hướng ngành 2017 mastercode.vn
Nghiên cứu về khách hàng mastercode.vn
Lập trình sáng tạo creative computing textbook mastercode.vn
Pd fbuoi2 onpage – tối ưu hóa trang web-mastercode.vn
Pdf buoi1 2-on-page-tran-ngoc-chinh-mastercode.vn
Pdfbài 5 bảo trì và tối ưu windows bảo trì sự cố máy tính-mastercode.vn
Pdfbài 4 ổ cứng hard drive bảo trì sự cố máy tính-mastercode.vn
Pdfbài 3 cpu và ram bảo trì sự cố máy tính-mastercode.vn
Pdfbài 1 giới thiệu chung về phần cứng bảo trì sự cố máy tính-mastercode.vn
Pdfbài 2 bo mạch chủ (main) bảo trì sự cố máy tính-mastercode.vn
Pdf bai 6 làm việc với truy vấn cơ bản-slide 06-quan tri csdl voi access-mast...
Pdf bai 5 làm việc với báo cáo nâng cao-slide 05-quan tri csdl voi access-mas...
Pdf bai 4 làm việc với báo cáo cơ bản-slide 04-quan tri csdl voi access-maste...
Pdf bai 3 làm việc với biểu mẫu nâng cao-slide 03-quan tri csdl voi access-ma...
Pdf bai 2 làm việc với biểu mẫu cơ bản-slide 02-quan tri csdl voi access-mast...
Pdf bai 1 tổng quan về ms access-quan tri csdl voi access-mastercode.vn
Pdf tim hieuc#vaungdung-mastercode.vn

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Classroom Observation Tools for Teachers
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Business Ethics Teaching Materials for college
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Cell Types and Its function , kingdom of life
VCE English Exam - Section C Student Revision Booklet
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPH.pptx obstetrics and gynecology in nursing
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Module 4: Burden of Disease Tutorial Slides S2 2025
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Classroom Observation Tools for Teachers
Microbial disease of the cardiovascular and lymphatic systems
Business Ethics Teaching Materials for college
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
TR - Agricultural Crops Production NC III.pdf
Complications of Minimal Access Surgery at WLH
STATICS OF THE RIGID BODIES Hibbelers.pdf

4 introduction-php-mvc-cakephp-m4-controllers-slides

  • 2. CakePHP Request  More Detailed Version of the CakePHP Request
  • 3. Routes  Parse the Request URL  Extracts parameters   e.g. controller, action, additional values passed in the URL. http://catalog/items/view/12  The Request URL Parameters are then Mapped to a Controller Action  A specific action in a specific controller class.    items controller view action (function) 12 value to use with the database
  • 4. Controller  The Controller Interacts With the Model   Controller calls on the model if there is a need to gain access to the application’s data. Model interacts with the database and returns data back to the controller.  The Controller then Interacts With the View   Controller can use the data from the model and manipulate it for the benefit of the view After the controller has the prepared the data, the controller passes the data off to the view
  • 6. A Tasty Example Model Route End User Controller View
  • 7. What’s In Store?  Continue Development of Our Catalog Web Site  DVDs, Books, CDs, etc.  Add to the Controller  Add Actions (functions) to the ItemsController we made in “Getting Started” module     Display a List all the Items Create and Delete an Item Update and Display a Detailed View of an Item Search the Items
  • 8. Setting Variables  Passing Variables to the View  The set() method is used to pass variables to the view.  First Parameter   Second parameter   Provide a name Provide the value or data Example  Controller   $this->set(‘pizza’, ‘pepperoni’); View  Their favorite pizza is <? echo $pizza; ?>.
  • 9. Query the Database  Accessing the Database Model in Controller  Access the Model via $this->ModelName  Example   $this->Item Retrieve Data from the Model Using find() Method  Example
  • 10. Query the Database  find() Parameters  First Parameter:   all / first / count / neighbors / list / threaded Second Parameter:  Array of Data   Example conditions / fields / joins / limit / offset / order / page / group / callbacks
  • 11. Single Query  Query Based on ID   findById() Example  $this->ModelName->findById($id);
  • 12. Throw an Exception  CakePHP Has Many Error Exceptions  http://book.cakephp.org/2.0/en/development/exceptions.html  Handling Errors   throw new NotFoundException Example  throw new NotFoundException(__(“Your item was not found”));
  • 13. Form Data  CakeRequest    Default request object in CakePHP. Passed by reference to the various layers of an application. Assigned to $this->request Example   Holds all the data from the form (modified and unmodified) $this->request->data  Check How the Data Was Sent   is() Takes One Parameter   post / get / put / delete / head / options / ajax / ssl / flash / mobile Example  $this->request->is(‘post’);
  • 14. Create & Save  Adding a New Item Into a Database    create() Resets the model state for saving new information. Clears out the model $id value Example  $this->ModelName->create();  Saving the Data   save() Parameters     1st : Array-formatted data to be saved. 2nd : Allows you to side step validation (bool) – optional 3rd : Supply a list of model fields to be saved. – optional Example  $this->ModelName->save($this->request->data);
  • 15. Redirect  Sending a User to a Different Page    Sometimes it is necessary redirect() Parameters:     Example     String action (if in same controller) Array controller & action Relative path $this->redirect(‘index’); $this->redirect(array( ‘controller’ => ‘Items’, ‘action’ => ‘index’)); $this->redirect(‘/Items/thanks’); More Redirect Examples  http://book.cakephp.org/2.0/en/controllers.html#flow-control
  • 16. Saving An Existing Entry  Saving an Item   Use the same save method that we utilized in the add() action, but we eliminate the need for the create() method to be called before hand. Example   $this->ModelName->save($this->request->data); Override the ‘id’ in our model  Example  $this->ModelName->id = $id;
  • 17. Populating the Form  Editing a Form   When you edit an item you need to populate the form with the content of the item you are editing. Example   $item = $this>ModelName->findById($id); $this->request->data = $item;
  • 18. Set and Display Message  Session Component  CakePHP provides a messaging system with the session component  Adding the Session Component to Your Controller  public $components = array('Session');  Using the Session Component  Example   $this->Session Access the Method   setFlash() Parameter   String message you want to display Example  $this->Session->setFlash(__(“Your record was saved.”));
  • 19. Does it Exist?  Previous Determination   $data = $this->ModelName->findById($id) if(!$data)  Throw Exception  Check to See if an Item Exists in the Database    exists() Returns Bool Value Parameters   $id (optional) Examples    $this->ModelName->exists($id); $this->ModelName->id = $id; $this->ModelName->exists()
  • 20. Delete Item  Deleting an Item in the Database    delete() Returns Bool Value Parameters   $id (optional) Examples    $this->ModelName->delete($id); $this->ModelName->id = $id; $this->ModelName->delete()
  • 21. Render Method  Normal Behavior  Calls the view template of the same name as the action   index() => index.ctp Called automatically at the end of the action in the controller  Override    Reuse, Plugins, Elements, etc. render() Parameter   Name of the template you would like to use Example   $this->render(‘index’); $this->render(‘/Cakes/index’);  app/View/Cakes/index
  • 22. Summary  A Review of the MVC Framework  Better understanding of the role of the controller  Added Actions (Functions) to Our Items Controller  Basic CRUD actions      Create Read Update Delete Search