Table of Contents : The Manual

The Manual

Click here for the CakePHP 1.1.x version of the manual

Welcome to the beta version of Cookbook, the new CakePHP documentation application. We hope this new application will serve to meet the following goals:

  • Make the process of contributing to the documentation easier.
  • Maintain a high level of quality, validity and accuracy for published documentation.

A huge thank you to AD7six, who championed the Cookbook cause by putting in endless hours developing, testing and improving this application.

How it Works:

  1. You visit the site and notice an error, something that is incomplete, something that hasn't been covered at all, or something that just isn't worded to your liking.
  2. Log in to Cookbook using your Bakery account.
  3. Submit additions/edits for review using valid, semantic HTML.
  4. Check back in the next day or so to see your changes approved.

This application is brand new, so we hope you'll be patient as we work out some final issues in preparation for the final release of CakePHP version 1.2.

How to Help:

Our main need is in getting the content from tempdocs.cakephp.org transposed to Cookbook. I've completed almost half of this task while testing Cookbook, so we're off to a great start. Please consider helping us achieve this goal by jumping in and marking up content.

A few tips:

  • Use the existing sections in Cookbook as an example.
  • Use the <pre> tag for code blocks.
  • Use valid, semantic HTML.
  • Do not be overly concerned with HTML formatting. I will fix whatever is submitted.

Translations

Email me (docs at cakephp dot org) or contact me on IRC (#cakephp on freenode) to discuss any translation efforts you would like to participate in.

Translator tips:


I'm committed to making the documentation for CakePHP better than it's ever been. I hope you'll join me by using this application and giving back to a project that we've all benefited so much from.

Sincerely,

John David Anderson aka _psychic_
(docs at cakephp dot org)
CakePHP Documentation

By _______________ on 12/2/08

1 - Wonderful!

Thanks for this good application and good framework regarding the doc effort. Do you plane to implement a history/changes feature?

Cheers.

By ceeram on 12/2/08

2 - great work

great work guys, i hope to be using it a lot, both reading and writing.

> and <h5> are very small for easily searching, bigger fontsize would improve quicksearch, especially when using "All in one page", which is already my favourite. What do i need a searchfunction for on the website when my browser has a nice one with CTRL+F :)

By janka on 14/2/08

3 - <code>

Very nice work indeed!!

But regarding "Use <pre> for code blocks" - how about the <code> tag instead?

Fits the "Use as plain and semantic HTML as you can" better :-)

By _______________ on 15/2/08

4 - <code> vs <pre>

Maybe is it possible to replace the <pre> in a DB dump?

By su6z3r0 on 15/2/08

5 - Please use Trac to submit enhancements

I don't think this is the right place to discuss styling/tagging etc. issues here.

By _______________ on 18/2/08

6 - <code> vs <pre>

No, su6z3r0

Look at http://bakery.cakephp.org/articles/view/what-s-up-docs

> If you notice an issue with the application, log a ticket at http://trac.cakephp.org.

> If you notice an issue with the documentation, make a suggestion via the 'book.

<pre> are in the doc not in the code. So this comment is in the right place here.

JakeCake

By su6z3r0 on 18/2/08

7 - Sorry, JakeCake

you are right! RTFM me :-)

But doesn't this spoil the whole comment thing? I mean in a few months no-one wants to dig through hundreds (hopefully :-)) of comments about tagging and styling issues which actually belong to this application and not cake itself.

By _______________ on 18/2/08

8 - <code> vs <pre>

No problem, su6z3r0. But what do you expect we comment here? We are speaking about the documentation strategy, not cakephp itself as you say. The <pre> are spread in all the documentation, so this root node is the right place to debate about it. The problem is not that we spoil, it's that we don't have any answer nor the possibility to replace <pre> by <code> in the database and adapt the CSS.

So, if help needed, Cookbook admins, I agree to give a little help on that and more. But maybe we are wrong with this issue. That's possible, just say it.

By AD7six on 19/2/08

9 - Wrong place

Chaps.

This is the wrong place to debate the way John has asked for content to be entered. In any event please look at the rendered souce (what a pre becomes) and you'll see that as well as code replacing pre not being appropriate, if you put code in a pre it gets marked up appropriately.

By tracyfloyd on 20/2/08

10 - Couple of UI tweak ideas

This is going to be great! I can't wait to get involved.

I've spent a little time with navigating around here are some of the things from a UI standpoint that I think needs some tweaking...

After browsing around a bit I think it will make for a easier navigation experience if we:

1. Repeat the chapter/section number notation in the red h2 headers... i.e. "1.3.1 Audience" instead of just "Audience" so that you can visually note where you are in the structure.

2. We need to figure out how to highlight the page you are currently viewing in the sidebar nav. I think just a simple background color on the list item may do the trick.

3. Currently, it looks like the top level list chapter numbers are not correct?

4. In the sidebar lists, an indented left margin denotes a subsection of the item above it (and rightly so, as we have all grown up with that type of structure). So thats great, but when a sub list item has sub items of its own, the triangle icon jacks up this structure visually and makes the whole thing harder to digest. For example, go to: http://book.cakephp.org/view/260/requiresecure Now, 5.2 looks like a sub item of 5.1 due to the left margin increase caused by the arrow icon. I think the easiest thing to do would be to give all list items an icon... the arrow if there are sub lists, and a similarly designed bullet or other symbol if there are not. This will help equalize the left margin spacing issue.

I've mocked up what I'm talking about here: http://files.cdnm.com/cakephp/UI-Ideas-01.png

I am happy to help with css on this if needed. Please let me know.

By tracyfloyd on 20/2/08

11 - Thoughts on comments

The "See Comments" link under the h2 section title title should also link down to the comments div. When you click it on a page (like this one) with a lot of content, it isn't obvious that you've "toggled" the display of the comments div... I would even consider tossing the toggle effect, leave the comments visible all the time and just make "See Comments" a link to an anchor so you jump down to the comments area... otherwise new users may miss out on a section's comments all together.

It might also be nice to have a little header above the comments area to separate it visually from the rest of the page's content.

By daibach on 21/2/08

12 - Output formats

What are the chances of getting some extra output formats of the cookbook manuals? It's be great to have an option for all-in-one-page HTML version, PDF etc...

I do a lot of development without internet access and having downloaded copies of manuals (like PHP and MySQL) is a great help. I currently rely on a saved copy of the tempdocs.cakephp site and it'd be great if I could easily export this site too.

Thanks

Dave

By jonathansnook on 21/2/08

13 - All in one page

daibach: there's a link in the sidebar that says "All in one page". Click on that and you'll get everything in one page. :)

By ceeram on 21/2/08

14 - all-in-one-page

@jonathansnook : i noticed that the option of all-in-one-page was gone for a day or so, now its back again.

By daibach on 22/2/08

15 - all-in-one-page

Oh aye!, blimey don't know how I missed that, sure I remember seeing it now.

Really helpful now, plus it's nice to see an overall look of everything so far.

Eventually it'd still be nice to have a different all-in-one-page option that has things rearranged or hidden. Like the contents list being at the top of the content instead of in the right column and the links hidden (like comments and edit). But this'll do for now :)

By mgrajcarek on 23/2/08

16 - Cookbook - when polish version?

Hi!

Cookbook is really great idea!

I would like to suggest adding also polish version. There is a constant growing CakePHP community in Poland and I'm sure there are many people who would like to participate in this project.

By bdude on 25/2/08

17 - Hide Comment/Edit Links

There should be an option to hide the comment/edit links when a user is just browsing and/or isn't logged in - or possibly hide them and show them onmouseover.

By avairet on 27/2/08

18 - Translate Cookbook menus

How can we translate the Cookbook menus, like "Table of contents", "See all comments", "Suggest a new section here"... ? There is no link for that.

In addition, how do you manage the new content added in English version for other languages? You rewrite the section in English and we re-translate all content?

Hope this comment is understandable...

By coolguru4ever 3 weeks, 2 days ago

19 - Problem with accessing 15 min Blog tutorial

I am new to CakePHP, so I was just starting with the 15 min Blog Tutorial that you have given.

I read it for 2 days, but today it is giving an error when I try to open the linked page.

Please check this problem...

By quayph 2 weeks ago

20 - CSS comments

I have noticed some possible improvements to the css.

When printing pages, the links to view comments or add a section could be hidden.

When I printed the Models section the menu took up 5 pages...

The code examples are printed twice, once for the formatted code with line numbers (the line numbers show up but the indentation doesn't) and once in the plain code (this prints correctly). I vote for only showing the plain code as printing in black and white makes the colouration and line numbers simply detract from he readability of the code.

In the screen stylesheet, the vertical margins and padding used for the plain text version of code examples are different from those used for the the formatted version. The result is that the total height of the example code changes when you mouse over a code example. Making the juggling the values so the total height of the example stayed the same as you mouse-over would make the change more 'seamless' and less tiring on the eyes.

To all the contributors to this manual: These comments are just details, you are doing an excellent job. The manual is clear and easy to use. Bravo. What more do you need?

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 since the material is what you're after, skip this superfluous section and dive right in.

By kmedlinnc on 3/4/08

1 - Is Preface "Superfluous?"

I might not position the first message the reader as, "Don't read this." What does everyone think of this instead:

Welcome to web development heaven!

CakePHP let's developers develop, designers design, and users use your masterpiece. Developers have literally dozens of PHP web application frameworks to choose from currently. CakePHP stands alone because it doesn't rely on multiple 3rd party frameworks to support core functionality, has a clear development support timeline, and has broad industry support from large scale projects.

You've come to the right place! A lot has changed since CakePHP 1.1 and we're excited to get you started learning CakePHP 1.2.

By kmedlinnc on 3/4/08

2 - err...

not "let's" just "lets" Missed that one in the proof.

Audience

This material is written for developers at all levels of ability; anyone who enjoys creating robust, maintainable applications quickly and effectively.

In order to understand the content of this document, you're going to need to have a working knowledge of PHP. Some basic familiarity with object-oriented programming will also help, though I suppose the introductory sections of this document could act as a primer of sorts.

There will be content that addresses technology which is technically beyond the scope of this document and not specific to the CakePHP framework. Some of these technologies include:

  • AJAX
  • JavaScript
  • SQL
  • Web Server Administration

Introduction to CakePHP

By earcanal on 26/2/08

1 - History

What happened to the history that's in the 1.1 manual? I'd like to know what came before cake, who baked it and why.

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:

  • Active, friendly community
  • Flexible licensing
  • Compatible with versions 4 and 5 of PHP
  • Integrated CRUD for database interaction
  • Application scaffolding
  • Code generation
  • MVC architecture
  • Request dispatcher with clean, custom URLs and routes
  • Built-in validation
  • Fast and flexible templating (PHP syntax, with helpers)
  • View Helpers for AJAX, JavaScript, HTML Forms and more
  • Email, Cookie, Security, Session, and Request Handling Components
  • Flexible ACL
  • Data Sanitization
  • Flexible Caching
  • Localization
  • Works from any web site directory, with little to no Apache configuration involved
Where to Get Help

The Cookbook

http://book.cakephp.org

You've started in the right place. This manual 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.

 

The API

http://api.cakephp.org/1.2

Straight to the point and straight from the core developers, the CakePHP API (Application Programming Interface) is the most comprehensive documentation around for all the nitty gritty details of the internal workings of the framework. Its a straight forward code reference, so bring your propeller hat.

 

The IRC channel

#cakephp @ irc.freenode.net

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.

 

The Bakery

http://bakery.cakephp.org

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

http://www.cakeforge.org

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

http://www.cakephp.org

The Official CakePHP website is always a great place to visit. It features links to oft-used developer tools, screencasts, donation opportunities, and downloads.

 

The Google Group

http://groups.google.com/group/cake-php

CakePHP also has a very active Google Group. It can be a great resource for finding archived answers, frequently asked questions, and getting answers to immediate problems.

 

Understanding Model-View-Controller

Overview

CakePHP follows the MVC software design pattern. Programming using MVC separates your application into three main parts:

  1. The Model represents the application data
  2. The View renders a presentation of model data
  3. The Controller handles and routes requests made by the client
Figure 1

Figure 1: A Basic MVC Request

Figure 1 shows an example of a bare-bones MVC request in CakePHP. To illustrate, assume a client named "Ricardo" just clicked on the “Buy A Custom Cake Now!” link on your application’s home page.

  • Ricardo clicks the link pointing to http://www.example.com/cakes/buy, and his browser makes a request to your web server.
  • The dispatcher checks the request URL (/cakes/buy), and hands the request to the correct controller.
  • The controller performs application specific logic. For example, it may check to see if Ricardo has logged in.
  • The controller also uses models to gain access to the application’s data. Models usually 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.
  • 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 client. Views in CakePHP are usually in HTML format, but a view could just as easily be a PDF, XML document, or JSON object depending on your needs.
  • 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 add some details later on which are specific to CakePHP, so keep this in mind as we proceed.

By Sake on 14/2/08

1 - Graphic missing

There seems to be a graphic from tempdocs missing. How do you enter graphics into the cookbook?

By ceeram on 20/2/08

2 - duplicate content

This part is also described in:

http://book.cakephp.org/view/21/a-typical-cakephp-request

although they differ a bit, i think one of them can be removed

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 application using CakePHP, you won't want to do it any other way.

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.

By thewoodman on 21/2/08

1 - Placement in TOC confusing?

It seems strange that the first thing I read in "CakePHP structure" is about Components etc... If reading the book through, you've barely been exposed to the concepts of the MVC, and now you're delving into behaviours!

And surely "Application Extensions" is also a little misleading, the base classes are not accurately described as 'extensions'?

Given all this, perhaps these should be moved into the Model, View and Controller sections, so they each have a section on their base class, and a section on how to extend them.

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:

  • beforeFilter(), executed before any controller action logic
  • beforeRender(), executed after controller logic, but before the view is rendered
  • 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:

  • beforeFind()
  • afterFind()
  • beforeValidate()
  • beforeSave()
  • afterSave()
  • beforeDelete()
  • 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.

  • app
  • cake
  • docs
  • index.php
  • 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 at the folders inside of app.

config
Holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.
controllers
Contains your application’s controllers and their components.
locale
Stores string files for internationalization.
models
Contains your application’s models, behaviors, and datasources.
plugins
Contains plugin packages.
tmp
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.
vendors
Any third-party classes or libraries should be placed here. Doing so makes them easy to access using the vendor() 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.
views
Presentational files are placed here: elements, error pages, helpers, layouts, and view files.
webroot
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.

Flow diagram showing a typical CakePHP request

Figure 2. Typical Cake Request.

Black = required element, Gray = optional element, Blue = callback

  1. Ricardo clicks the link pointing to http://www.example.com/cakes/buy, and his browser makes a request to your web server.
  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. 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. 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. After the model has retrieved the data, it is returned to the controller. Model callbacks may apply.
  6. The controller may use components to further refine the data or perform other operations (session manipulation, authentication, or sending emails, for example).
  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. 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 and 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 and Database 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.

Foreign keys in hasMany, belongsTo or hasOne relationships are recognized by default as the (singular) name of the related model followed by _id. So if a baker hasMany cakes, the cakes table will refer to the baker in the bakers table via a baker_id foreign key.

Join tables, used in hasAndBelongsToMany (HABTM) relationships between models should be named after the model tables they will join in alphabetical order (apples_zebras rather than zebras_apples).

All tables CakePHP models interact with (with the exception of join tables), require a singular primary key to uniquely identify each row. If you wish to model a table which does not have a single-field primary key, such as the rows of your posts_tags join table, CakePHP's convention is that a single-field primary key is added to the table.

By crankshaft on 10/4/08

1 - Consistency?

How come Cake fails to follow its own conventions... Shouldn't the ACL join table be named acos_aros, not aros_acos? :-)

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.

By Falise.com 8 hours, 5 minutes ago

1 - Plurar

"Controller classnames are plural", so shouldn't it be PeoplesController, BigPeoplesController, and ReallyBigPeoplesController?

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

  • Database table: ‘people’
  • Model class: ‘Person’, found at /app/models/person.php
  • Controller class: ‘PeopleController’, found at /app/controllers/people_controller.php
  • 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

  • HTTP Server. Apache with mod_rewrite is preferred, but by no means required.
  • 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:

  • MySQL (4 or greater)
  • PostgreSQL
  • Firebird DB2
  • Microsoft SQL Server
  • Oracle
  • SQLite
  • ODBC
  • ADOdb

Installation Preparation

By thewoodman on 16/2/08

1 - Reorder in TOC?

I think having installation details, and config details, coming under "Developing with CakePHP" is confusing, and distracts from the topics that really are about development.

Surely "Installing and Configuring CakePHP" should be its own section, before "Developing With..." ?

By tman 10 hours, 54 minutes ago

2 - I'll second that

I've been running around in circles trying to install Cake, and I'm still running! Why is Installation buried away in section 3? Installation should be the *very first link* in the documentation. And this section, "Installation Preparation", is where the discussion about .htaccess files and mod_rewrite belongs, because those issues need to be understood before installation can proceed. I'm using a web hosting company, have no access to the http.conf file, and have been frustrated by the lack of clear documentation on how to get Cake installed. I read that it works without mod_rewrite, but what do I need to do to configure that? Why isn't that explained in this section? I'm a web site developer, not an Apache guru!

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.

  • Development: easy to get going, URLs for the application include the CakePHP installation directory name, and less secure.
  • Production: Requires the ability to configure the web server’s document root, clean URLs, very secure.
  • 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.

By xentek on 23/2/08

1 - Advanced Installation

In a typical shared hosting environment, you get a path like this for your vhosts:

/var/www/vhosts/site_name.com/

This is an ideal location for storing the core cake lib and other code that doesn't need to be in the webroot.

But the biggest limitation is that the host has your the document root for the vhost configured:

/var/www/vhosts/site_name.com/htdocs

Since other stuff on the system depends on a standard location for each site (especially control panel software like Plesk, CPanel, and the like), you can't really modify this.

What I'd like to see in this section is how you can adapt CakePHP to treat the htdocs folder as the web root, and be able to install all the other files outside of the webroot. The Advanced Install section starts to address this, but doesn't tell you where to put the index.php, and vendors folder.

Ideally, I see it looking something like this:

/var/www/vhosts/site_name.com/cakephp

Which has the app folder, the cake folder (which could optionally mapped elsewhere, if you wanted this to be a 'universal' library for the whole server), index.php (probably not needed), and docs.

The app/webroot folder would be mapped to /var/www/vhosts/site_name.com/htdocs

However it is unclear how one would actually do this in the current docs. Maybe the approach should be in telling the user how it finds each folder, and how you might actually go about telling it where to find the ones you want to use. But the biggest question that's left for me is, can you 'rename' the webroot folder... so that it can be called whatever your host forces you to call it?

I don't know... maybe its just as easy as uploading the contents of /cakephp to /var/www/vhosts/site_name.com and putting everything in app at /var/www/vhosts/site_name.com/htdocs and mapping it to this folder with the ROOT, and APP_DIR constants... But the docs don't really let me know if this would be possible.

By mardala on 23/3/08

2 - Here is what I did

Note, this is not tested beyond just an installation. ie, I haven't built a fully functioning site using cake so I haven't tested all possibilities of modifying the path tree. But ... with a few slight modifications I was able to setup cake so it existed under a new structure.

> should now point to where CAKE is located.

I defined > if you have ini_set it goes to null .. but I set it to: CAKE_CORE_INCLUDE_PATH.DS."mvc".DS

5. Modify this in paths.php:

APP --> I set it to MVC_APP.DS

Thats it. But note I haven't actually built anything yet, this is just a default installation. But I think its easy enough if you run into a path issue to fix it.

By mardala on 23/3/08

3 - Oops

Most of my example was deleted thru when it was posted. So I put it up here:

http://john.mardala.com/cake.txt

By kmedlinnc on 8/4/08

4 - Tutorial from my Blog

You are more than welcome to have the tutorial from my blog for this project. It covers rather more than just the installation, but you could easily take that piece out and post it here.

http://keithmedlin.com/?p=26

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:

  • /var/www/html
    • /cake_1_2
      • /app
      • /cake
      • /docs
      • /index.php
      • /vendors

To see your CakePHP application, point your web browser to http://www.example.com/cake_1_2/

By tracyfloyd on 20/2/08

1 - list item bullets are confusing

These list item bullets are confusing... In the right sidebar, these are clickable... but here they are not. I think I would use a different icon and reserve these arrows for lists that have the jquery treeview functionality so that things stay consistent.

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:

  • /path_to_cake_install/
  • /app
    • /webroot (this directory is set as the document root for the web server)
  • /cake
  • /docs
  • /index.php
  • /vendors

If this application was going to be hosted on Apache, the DocumentRoot directive for the domain would look something like:

DocumentRoot /path_to_cake_install/app/webroot
  1. DocumentRoot /path_to_cake_install/app/webroot

To see your CakePHP application, point your web browser to http://www.example.com.

Advanced Installation

There may be some situations where you wish to place CakePHP's directories on different places on the filesystem. This may be due to a shared host restriction, or maybe you just want a few of your apps to share the same Cake libraries. This section describes how to spread your CakePHP directories across a filesystem.

First, realize that there are three main parts to a Cake application:

  1. The core CakePHP libraries, in /cake.
  2. Your application code, in /app.
  3. The application’s webroot, usually in /app/webroot.

Each of these directories can be located anywhere on your file system, with the exception of the webroot, which needs to be accessible by your web server. You can even move the webroot folder out of the app folder as long as you tell Cake where you've put it.

To configure your Cake installation, you'll need to make some changes to /app/webroot/index.php. There are three constants that you'll need to edit: ROOT, APP_DIR, and CAKE_CORE_INCLUDE_PATH.

  • ROOT should be set to the path of the directory that contains your app folder.
  • APP_DIR should be set to the path of your app folder.
  • CAKE_CORE_INCLUDE_PATH should be set to the path of your CakePHP libraries folder.

Let’s run through an example so you can see what an advanced installation might look like in practice. Imagine that I wanted to set up CakePHP to work as follows:

  • The CakePHP core libraries will be placed in /usr/lib/cake.
  • My application’s webroot directory will be /var/www/mysite/.
  • My application’s app directory will be stored in /home/me/mysite.

Given this type of setup, I would need to edit my webroot/index.php file (which will end up at /var/www/mysite/index.php, in this example) to look like the following:

// /app/webroot/index.php (partial, comments removed) 

if (!defined('ROOT')) {
    define('ROOT', DS.'home'.DS.'me');
}

if (!defined('APP_DIR')) {
    define ('APP_DIR', 'mysite');
}

if (!defined('CAKE_CORE_INCLUDE_PATH')) {
    define('CAKE_CORE_INCLUDE_PATH', DS.'usr'.DS.'lib'.DS.'cake');
}
  1. // /app/webroot/index.php (partial, comments removed)
  2. if (!defined('ROOT')) {
  3. define('ROOT', DS.'home'.DS.'me');
  4. }
  5. if (!defined('APP_DIR')) {
  6. define ('APP_DIR', 'mysite');
  7. }
  8. if (!defined('CAKE_CORE_INCLUDE_PATH')) {
  9. define('CAKE_CORE_INCLUDE_PATH', DS.'usr'.DS.'lib'.DS.'cake');
  10. }

It is recommended to use the DS constant rather than slashes to delimit file paths. This prevents any missing file errors you might get as a result of using the wrong delimiter, and it makes your code more portable.

Additional Class Paths

It’s occasionally useful to be able to share MVC classes between applications on the same system. If you want the same controller in both applications, you can use CakePHP’s bootstrap.php to bring these additional classes into view.

In bootstrap.php, define some specially-named variables to make CakePHP aware of other places to look for MVC classes:

$viewPaths        = array();
$controllerPaths  = array();
$modelPaths       = array();
$helperPaths      = array();
$componentPaths   = array();
$behaviorPaths    = array();
  1. $viewPaths = array();
  2. $controllerPaths = array();
  3. $modelPaths = array();
  4. $helperPaths = array();
  5. $componentPaths = array();
  6. $behaviorPaths = array();

Each of these special variables can be set to an array of absolute filesystem paths where extra classes can be found when requested. Make sure that each path specified includes a trailing slash.

Apache and mod_rewrite

While CakePHP is built to work with mod_rewrite out of the box–and usually does–we've noticed that a few users struggle with getting everything to play nicely on their systems. Here are a few things you might try to get it running correctly:

  • Make sure that an .htaccess override is allowed. In your httpd.conf, you should have a section that defines your Directory on the server. Make sure the AllowOverride is set to All for the correct DocumentRoot.
  • Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.
  • Is CakePHP missing its needed .htaccess files? This sometimes happens during copying or moving because some operating systems treat files that start with '.' as hidden. Make sure your copy of CakePHP is from the downloads section of the site or our SVN repository, and has been unpacked correctly.
  • Make sure you are loading up mod_rewrite correctly. You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so and AddModule mod_rewrite.c in your httpd.conf.
  • If you are installing CakePHP into a user directory (http://example.com/~username), you'll need to modify the .htaccess file in the base directory of your CakePHP installation. Just add the line "RewriteBase /~myusername/".
Fire It Up

Alright, let's see CakePHP in action. Depending on which setup you used, you should point your browser to http://example.com/ or http://example.com/cake_install/. At this point, you'll be presented with CakePHP's default home, and a message that tells you the status of your current database connection.

Congratulations! You are ready to create your first CakePHP application.

Configuration

 
Database Configuration

CakePHP expects database configuration details to be in a file at app/config/database.php. An example database configuration file can be found at app/config/database.php.default. A finished configuration should look something like this.

var $default = array('driver'      => 'mysql',
                     'persistent'  => false,
                     'host'        => 'localhost',
                     'login'       => 'cakephpuser',
                     'password'    => 'c4k3roxx!',
                     'database'    => 'my_cakephp_project',
                     'prefix'      => '');
  1. var $default = array('driver' => 'mysql',
  2. 'persistent' => false,
  3. 'host' => 'localhost',
  4. 'login' => 'cakephpuser',
  5. 'password' => 'c4k3roxx!',
  6. 'database' => 'my_cakephp_project',
  7. 'prefix' => '');

The $default connection array is used unless another connection is specified by the $useDbConfig property in a model. For example, if my application has an additional legacy database in addition to the default one, I could use it in my models by creating a new $legacy database connection array similar to the $default array, and by setting var $useDbConfig = ‘legacy’; in the appropriate models.

Fill out the key/value pairs in the configuration array to best suit your needs.

Key Value
driver The name of the database driver this configuration array is for. Examples: mysql, postgres, sqlite, pear-drivername, adodb-drivername, mssql, oracle, or odbc.
persistent Whether or not to use a persistent connection to the database.
host The database server’s hostname (or IP address).
login The username for the account.
password The password for the account.
database The name of the database for this connection to use.
prefix (optional) The string that prefixes every table name in the database. If you’re tables don’t have prefixes, set this to an empty string.
port (optional) The TCP port or Unix socket used to connect to the server.
encoding Indicates what character set the to use to send SQL statements to the server.
schema Used in PostgreSQL database setups to specify which schema to use.

Note that the prefix setting is for tables, not models. For example, if you create a join table for your Apple and Flavor models, you name it prefix_apples_flavors (not prefix_apples_prefix_flavors), and set your prefix setting to ‘prefix_’.

At this point, you might want to take a look at the CakePHP Conventions, listed in an appendix to this manual. The correct naming for your tables (and the addition of some columns) can score you some free functionality and help you avoid configuration.

Core Configuration

Application configuration in CakePHP is found in /app/config/core.php. This file is a collection of Configure class variable definitions and constant definitions that determine how your application behaves. Before we dive into those particular variables, you’ll need to be familiar with Configure, CakePHP’s configuration registry class.

The Configuration Class

Despite few things needing to be configured in CakePHP, it’s sometimes useful to have your own configuration rules for your application. In the past you may have defined custom configuration values by defining variable or constants in some files. Doing so forces you to include that configuration file every time you needed to use those values.

CakePHP’s new Configure class can be used to store and retrieve application or runtime specific values. Be careful, this class allows you to store anything in it, then use it in any other part of your code: a sure temptation to break the MVC pattern CakePHP was designed for. The main goal of Configure class is to keep centralized variables that can be shared between many objects. Remember to try to live by "convention over configuration" and you wont end up breaking the MVC structure we’ve set in place.

This class acts as a singleton and its methods can be called from anywhere within your application, in a static context.

<?php Configure::read('debug'); ?>
  1. <?php Configure::read('debug'); ?>
Configure Methods

write
write(string $key, mixed $value)
  1. write(string $key, mixed $value)

Use write() to store data in the application’s configuration.

Configure::write('Company.name','Pizza, Inc.');
Configure::write('Company.slogan','Pizza for your body and soul');
  1. Configure::write('Company.name','Pizza, Inc.');
  2. Configure::write('Company.slogan','Pizza for your body and soul');

Note the usage of dot notation in the $key parameter. You can use this notation to organize your configuration into logical groups.

The above example could also be written in a single call:

Configure::write(
    'Company',array('name'=>'Pizza, Inc.','slogan'=>'Pizza for your body and soul')
);
  1. Configure::write(
  2. 'Company',array('name'=>'Pizza, Inc.','slogan'=>'Pizza for your body and soul')
  3. );

You can use Configure::write(‘debug’, $int) to switch between debug and production modes on the fly. This is especially handy for AMF or SOAP interactions where debugging information can cause parsing problems.

read
read(string $key = 'debug')
  1. read(string $key = 'debug')

Used to read configuration data from the application. Defaults to CakePHP’s important debug value. If a key is supplied, the data is returned. Using our examples from write() above, we can read that data back:

Configure::read('Company.name');    //yields: 'Pizza, Inc.'
Configure::read('Company.slogan');  //yields: 'Pizza for your body and soul'
 
Configure::read('Company');
 
//yields: 
array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul');
  1. Configure::read('Company.name'); //yields: 'Pizza, Inc.'
  2. Configure::read('Company.slogan'); //yields: 'Pizza for your body and soul'
  3. Configure::read('Company');
  4. //yields:
  5. array('name' => 'Pizza, Inc.', 'slogan' => 'Pizza for your body and soul');
delete
delete(string $key)
  1. delete(string $key)

Used to delete information from the application’s configuration.

Configure::delete('Company.name');
  1. Configure::delete('Company.name');
load
load(string $path)
  1. load(string $path)

Use this method to load configuration information from a specific file.

// /app/config/messages.php:
<?php
$config['Company']['name'] = 'Pizza, Inc.';
$config['Company']['slogan'] = 'Pizza for your body and soul';
$config['Company']['phone'] = '555-55-55';
?>
 
<?php
Configure::load('messages');
Configure::read('Company.name');
?>
  1. // /app/config/messages.php:
  2. <?php
  3. $config['Company']['name'] = 'Pizza, Inc.';