CAKEphp 1.2
The Good Stuff
 
 
Folks: Since the launch of our new Cookbook application, we need as much help as possible moving content from here over to http://book.cakephp.org . Please consider taking some time and entering in a section or so.
 Note: please move over one section at a time. If your submission has any header tags (h1, h2, etc.) that means you’ve entered more than you should. Check the structure over at the Cookbook, and move things over a bit at a time.
Thanks for your help and support.
-- John
Beginning With CakePHP
Patty-cake, patty-cake...
Preface
Welcome to web development heaven.
If you’re reading the preface to a technical manual, you probably have too much time on your hands. We’re not celebrities, and the material is what you’re after, so skip this superfluous section and dive right in.
Audience
In order to read this manual, you’re going to need to be moderately familiar with PHP. Some familiarity with object-oriented programming will help, though I suppose the introductory sections of this manual could act as a primer of sorts. That said, this material is written to developers of all levels of ability–anyone who wants to create robust, maintainable applications quickly and enjoyably.
I should say that there will be sections that address technologies that are really out of the scope of this manual. Web server administration, AJAX and JavaScript details and the like may be touched on in places, but for the most part we’re just going to stick to CakePHP.
Introduction to CakePHP
What is CakePHP? Why Use it?
CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. Our primary goal is to enable you to work in a structured and rapid manner–without loss of flexibility.
CakePHP takes the monotony out of web development. We provide you with all the tools  you need to get started coding what you really need to get done: the logic specific to your application. Instead of reinventing the wheel every time you sit down to a new project, check out a copy of CakePHP and get started with the real guts of your application.
CakePHP has an active developer team and community, bringing great value to the project. In addition to keeping you from wheel-reinventing, using CakePHP means your application’s core is well tested and is being constantly improved.
Here’s a quick list of features you’ll enjoy when using CakePHP:
  1. Active, friendly community
  2. Flexible licensing
  3. Compatible with PHP4 and PHP5
  4. Integrated CRUD for database interaction
  5. Application scaffolding
  6. Code generation
  7. Model View Controller (MVC) architecture
  8. Request dispatcher with clean, custom URLs and routes
  9. Built-in validation
  10. Fast and flexible templating (PHP syntax, with helpers)
  11. View Helpers for AJAX, JavaScript, HTML Forms and more
  12. Email, Cookie, Security, Session, and Request Handling Components
  13. Flexible access control lists
  14. Data Sanitization
  15. Flexible Caching
  16. Localization
  17. Works from any web site subdirectory, with little to no Apache configuration involved
Where to Get Help
You’ve started in the right place. This manual (and the API) should probably be the first place you go to get answers. As with many other open source projects, we get new folks regularly. Try your best to answer your questions on your own first. Answers may come slower, but will remain longer–and you’ll also be lightening our support load. Both the manual and the API have an online component.
If you’re stumped, give us a holler in the CakePHP IRC channel. Someone from the development team is usually there, especially during the daylight hours for North and South America users. We’d love to hear from you, whether you need some help, want to find users in your area, or would like to donate your brand new sports car.
#cakephp @ irc.freenode.net
The CakePHP Bakery is a clearing house for all things CakePHP. Check it out for tutorials, case studies, and code examples. Once you’re acquainted with CakePHP, log on and share your knowledge with the community and gain instant fame and fortune.
CakeForge is another developer resource you can use to host your CakePHP projects to share with others. If you’re looking for (or want to share) a killer component or a praiseworthy plugin, check out CakeForge.
The Official CakePHP website is always a great place to visit. It features links to oft-used developer tools, screencasts, donation opportunities, and downloads.
Understanding Model-View-Controller
Overview
Well-written CakePHP applications follow the MVC (Model-View-Controller) software design pattern. Programming using MVC separates your application into three main parts. The model represents an application’s data, the view renders a presentation of model data, and the controller handles and routes requests made by users.
Figure 1: A Basic MVC Request
 
Figure 1 shows an example of a bare-bones MVC request in CakePHP. For illustrative purposes, let’s say a user named Ricardo just clicked on the “Buy A Custom Cake Now!” link on your application’s landing page.
  1. 1.Ricardo clicks the link pointing to http://www.example.com/cakes/buy, and his browser makes a request to your web server.
  2. 2.The dispatcher checks the request URL (/cakes/buy), and hands the request to the correct controller.
  3. 3.The controller performs application specific logic. For example, it may check to see if Ricardo has logged in.
  4. 4.The controller also uses models to gain access to the application’s data. Most often, models represent database tables, but they could also represent LDAP entries, RSS feeds, or files on the system. In this example, the controller uses a model to fetch Ricardo’s last purchases from the database.
  5. 5.Once the controller has worked its magic on the data, it hands it to a view. The view takes this data and gets it ready for presentation to the user. Views in CakePHP most often come in HTML format, but a view could as easily be a PDF, XML document, or JSON object depending on your needs.
  6. 6.Once the view has used the data from the controller to build a fully rendered view, the content of that view is returned to Ricardo’s browser.
Almost every request to your application will follow this basic pattern. We’ll fill in some Cake-specific details later on, so keep this in the back of your mind as we move on.
Benefits
Why use MVC? Because it is a tried and true software design pattern that turns an application into a maintainable, modular, rapidly developed package. Crafting application tasks into separate models, views, and controllers makes your application very light on its feet. New features are easily added, and new faces on old features are a snap. The modular and separate design also allows developers and designers to work simultaneously, including the ability to rapidly prototype. Separation also allows developers to make changes in one part of the application without affecting others.
If you’ve never built an application this way, it takes some getting used to, but we’re confident that once you’ve built your first CakePHP application, you won’t want to go back.
Basic Principles of CakePHP
The Start of Becoming a Smart Cookie
CakePHP Structure
CakePHP features Controller, Model, and View classes, but it also features some additional classes and objects that make development in MVC a little quicker and more enjoyable. Components, Behaviors, and Helpers are classes that provide extensibility and reusability to quickly add functionality to the base MVC classes in your applications. Right now we’ll stay at a higher level, so look for the details on how to use these tools later on.
Controller Extensions
A Component is a class that aids in controller logic. If you have some logic you want to share between controllers (or applications), a component is usually a good fit. As an example, the core EmailComponent class makes creating and sending emails a snap. Rather than writing a controller method in a single controller that performs this logic, you can package the logic so it can be shared.
Controllers are also fitted with callbacks. These callbacks are available for your use, just in case you need to insert some logic between CakePHP’s core operations. Callbacks available include:
  1. beforeFilter(), executed before any controller action logic
  2. beforeRender(), executed after controller logic, but before the view is rendered
  3. afterFilter(), executed after all controller logic, including the view render. There may be no difference between afterRender() and afterFilter() unless  you’ve manually made a call to render() in your controller action and have included some logic after that call.
View Extensions
A Helper is a class that aids in view logic.  Much like a component used among controllers, helpers allow presentational logic to be accessed and shared between views. One of the core helpers, AjaxHelper, makes Ajax requests within views much easier.
Most applications have pieces of view code that are used repeatedly. CakePHP facilitates view code reuse with layouts and elements. By default, every view rendered by a controller is placed inside a layout. Elements are used when small snippets of content need to be reused in multiple views.
Model Extensions
Similarly, Behaviors work as ways to add common functionality between models. For example, if you store user data in a tree structure, you can specify your User model as behaving like a tree, and gain free functionality for removing, adding, and shifting nodes in your underlying tree structure.
Models also are supported by another class called a DataSource. DataSources are an abstraction that enable models to manipulate different types of data consistently. While the main source of data in a CakePHP application is often a database, you might write additional DataSources that allow your models to represent RSS feeds, CSV files, LDAP entries, or iCal events. DataSources allow you to associate records from different sources: rather than being limited to SQL joins, DataSources allow you to tell your LDAP model that it is associated to many iCal events.
Just like controllers, models are featured with callbacks as well:
  1. beforeFind()
  2. afterFind()
  3. beforeValidate()
  4. beforeSave()
  5. afterSave()
  6. beforeDelete()
  7. afterDelete()
The names of these methods should be descriptive enough to let you know what they do. Be sure to get the details in the models chapter.
Application Extensions
Both controllers, helpers and models have a parent class you can use to define application-wide changes. AppController (located at /app/app_controller.php), AppHelper (located at /app/app_helper.php) and AppModel (located at /app/app_model.php) are great places to put methods you want to share between all controllers, helpers or models.
Although they aren’t a class or file, routes play a role in requests made to CakePHP. Route definitions tell CakePHP how to map URLs to controller actions. The default behavior assumes that the URL “/controller/action/var1/var2” maps to Controller::action($var1, $var2), but you can use routes to customize URLs and how they are interpreted by your application.
Some features in an application merit packaging as a whole. A plugin is a package of models, controllers and views that accomplish a specific purpose that can span multiple applications. A user management system or a simplified blog might be good fits for CakePHP plugins.
CakePHP File Structure
Let’s take a look at what CakePHP looks like right out of the box. You know what CakePHP looks like from a basic MVC request standpoint, but  you’ll need to know how its files are organized as well.
  1. app            
  2. cake
  3. docs
  4. index.php
  5. vendors
When you download CakePHP, you will see four main folders. The app folder will be where you work your magic: it’s where your application’s files will be placed. The cake folder is where we’ve worked our magic. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core. The docs folder is for the quintessential readme, changelog, and licensing information. Finally, the vendors folder is where you’ll place third-party PHP libraries you need to use with your CakePHP applications.
The App Folder        
CakePHP’s app folder is where you will do most of your application development. Let’s look a little closer and the folders inside of app.
  1. config
    1. Holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.        
  2. controllers    
    1. Contains your application’s controllers and their components.
  3. locale
    1. Stores string files for internationalization.
  4. models
    1. Contains your application’s models, behaviors, and datasources.        
  5. plugins
    1. Contains plugin packages.
  6. tmp
    1. This is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions, logs, and sometimes session information.
  7. vendors
    1. Any third-party classes or libraries should be placed here. Doing so makes them easy to access using the vendors() function. Keen observers will note that this seems redundant, as there is also a vendors folder at the top level of our directory structure.  We'll get into the differences between the two when we discuss managing multiple applications and more complex system setups.
  8. views
    1. Presentational files are placed here: elements, error pages, helpers, layouts, and view files.
  9. webroot
    1. In a production setup, this folder should serve as the document root for your application. Folders here also serve as holding places for CSS stylesheets, images, and JavaScript files.
A Typical CakePHP Request
We’ve covered the basic ingredients in CakePHP, so let’s look at how each object works together to complete a basic request. Continuing with our original request example, let’s imagine that our friend Ricardo just clicked on the “Buy A Custom Cake Now!” link on a CakePHP application’s landing page.
Figure 2. Typical Cake Request.
Black = required element, Gray = optional element, Blue = callback
  1. 1.Ricardo clicks the link pointing to http://www.example.com/cakes/buy, and his browser makes a request to your web server.
  2. 2.The Router parses the URL in order to extract the parameters for this request: the controller, action, and any other arguments that will affect the business logic during this request.
  3. 3.Using routes, a request URL is mapped to a controller action (a method in a specific controller class). In this case, it’s the buy() method of the CakesController. The controller’s beforeFilter() callback is called before any controller action logic is executed.
  4. 4.The controller may use models to gain access to the application’s data. In this example, the controller uses a model to fetch Ricardo’s last purchases from the database. Any applicable model callbacks, behaviors, and DataSources may apply during this operation. While model usage is not required, all CakePHP controllers initially require at least one model.
  5. 5.After the model has retrieved the data, it is returned to the controller. Model callbacks may apply.
  6. 6.The controller may use components to further refine the data or perform other operations (session manipulation, authentication, or sending emails, for example).
  7. 7.Once the controller has used models and components to prepare the data sufficiently, that data is handed to the view using the controller’s set() method. Controller callbacks may be applied before the data is sent. The view logic is performed, which may include the use of elements and/or helpers. By default, the view is rendered inside of a layout.
  8. 8.Additional controller callbacks (like afterFilter) may be applied. The complete, rendered view code is sent to Ricardo’s browser.
CakePHP Conventions
We’re a big fan of convention over configuration. While it takes a bit of time to learn CakePHP’s conventions, you save time in the long run: by following convention, you get free functionality, and you free yourself from the maintenance nightmare of tracking config files. Convention also makes for a very uniform system development, allowing other developers to jump in an help more easily.
CakePHP’s conventions have been distilled out of years of web development experience and best practices. While we suggest you use these conventions while developing with CakePHP, we should mention that many of these tenets are easily overridden–something that is especially handy when working with legacy systems.
File and Classname Conventions
In general, filenames are underscored, while classnames are CamelCased. The class KissesAndHugsController can be found in the file kisses_and_hugs_controller.php, for example.
The name of the class a file holds may not necessarily be found in the filename, however. The class EmailComponent is found in a file named email.php, and the class HtmlHelper is found in a file named html.php.
Model Conventions
Model classnames are singular and CamelCased. Person, BigPerson, and ReallyBigPerson are all examples of conventional model names.
Table names corresponding to CakePHP models are plural and underscored. The underlying tables for the above mentioned models would be people, big_people, and really_big_people, respectively.
Join tables, used in hasAndBelongsToMany relationships between models should be named after the model tables they will join, in alphabetical order (apples_zebras rather than zebras_apples). If your application features this type of relationship between your Tag and Post models, the table name would be posts_tags.
Controller Conventions
Controller classnames are plural, CamelCased, and end in ‘Controller.’ PeopleController, BigPeopleController, and ReallyBigPeopleController are all examples of conventional controller names.
The first function you write for a controller might be the index() function. When a request specifies a controller but not an action, the default CakePHP behavior is to render the index() function of that controller. For example, a request to http://www.example.com/apples/ maps to a call on the index() function of the ApplesController, where as http://www.example.com/apples/view maps to a call on the view() function of the ApplesController.
You can also change the visibility of controller functions in CakePHP by prepending controller function names with underscores. If a controller function has been prepended with an underscore, the function will not be web-viewable through the dispatcher, but is available for internal use.
View Conventions
View template files are named after the controller functions they display, in an underscored form. The getReady() function of the PeopleController class will look for a view template in /app/views/people/get_ready.ctp.  
The basic pattern is /app/views/controller/underscored_function_name.ctp.
By naming the pieces of your application using CakePHP conventions, you gain functionality without the hassle and maintenance tethers of configuration. Here’s a final example that ties the conventions
  1. Database table: ‘people’
  2. Model class: ‘Person’, found at /app/models/person.php
  3. Controller class: ‘PeopleController’, found at /app/controllers/people_controller.php
  4. View template, found at /app/views/people/index.ctp
Using these conventions, CakePHP knows that a request to http://example.com/people/ maps to a call on the index() function of the PeopleController, where the Person model is automatically available (and automatically tied to the ‘people’ table in the database), and renders to a file. None of these relationships have been configured by any means other than by creating classes and files that you’d need to create anyway.
 
Now that you’ve been introduced to CakePHP’s fundamentals, you might try a run through the CakePHP Blog Tutorial, an appendix at the end of this manual.
Developing with CakePHP
Now you’re cooking.
Requirements
  1. HTTP Server. Apache with mod_rewrite is preferred, but by no means required.
  2. PHP 4.3.2 or greater. Yes, CakePHP works great on PHP 4 and 5.
Technically a database engine isn’t required, but we imagine that most applications will utilize one. CakePHP supports a variety of database storage engines:
  1. MySQL (4 or greater)
  2. PostgreSQL
  3. Firebird DB2
  4. Microsoft SQL Server
  5. Oracle
  6. SQLite
  7. ODBC
  8. ADOdb
Installation Preparation
Getting CakePHP
There are two main ways to get a fresh copy of CakePHP. First,  you can download an archive (zip/tar.gz/tar.bz2), or you can check out a code from our repository (SVN).
To get a fresh archive, visit our web site at http://www.cakephp.org. Follow the huge “Download Now!” link to paradise. CakePHP downloads are hosted at CakeForge, and you can also visit the project web site at http://cakeforge.org/projects/cakephp.
If you want to live on the edge, check out our nightly downloads at http://cakephp.org/downloads/index/nightly. CakePHP nightlies are stable, and include fixes between releases.
To grab a fresh copy from our SVN repository, connect to https://svn.cakephp.org/repo/branches/1.2.x.x .
Permissions
CakePHP uses the /app/tmp directory for a number of different operations. Model descriptions, cached views, and session information are just a few examples.
As such, make sure the /app/tmp directory in your cake installation is writable by the web server user.
Installation
Installing CakePHP can be as simple as slapping it in your web server’s document root, or as complex and flexible as you wish. This section will cover the three main installation types for CakePHP: development, production, and advanced.
  1. Development: easy to get going, URLs for the application include the CakePHP installation directory name, and less secure.
  2. Production: Requires the ability to configure the web server’s document root, clean URLs,  very secure.
  3. Advanced: With some configuration, allows you to place key CakePHP directories in different parts of the filesystem, possibly sharing a single CakePHP core library folder amongst many CakePHP applications.
Development
Just place  your cake install inside your web server’s document root. For example, assuming your web server’s document root is /var/www/html, a development setup would look like this on the filesystem:
  1. /var/www/html
    1. /cake
      1. /app            
      2. /cake
      3. /docs
      4. /index.php
      5. /vendors
To see your CakePHP application, point your web browser to http://www.example.com/cake/.
Production
In order to utilize a production setup, you will need to have the rights to change the document root for your web server. Choosing the production setup means the whole domain acts as a single CakePHP application.
The production setup uses the following layout:
  1. /path_to_cake_install/
    1. /app
      1. /webroot (this directory is set as the document root for the web server)
    2. /cake
    3. /docs
    4. /index.php
    5. /vendors
If this application was going to be hosted on Apache, the DocumentRoot directive for the d