CakePHP - Cookbook 1.2, CakePHP
[ Pobierz całość w formacie PDF ]
Cookbook :: 1.2 Collection :: The Manual
The Manual
Click here for the CakePHP 1.1.x version of the manual
Welcome to the Cookbook, the CakePHP documentation. The Cookbook is a wiki-like system allowing contributions from the public.
With an open system, we hope to maintain a high level of quality, validity, and accuracy for the CakePHP documentation. The
Cookbook also makes it easy for anybody to contribute.
A
huge
thank you to
AD7six
, who championed the Cookbook by putting in endless hours developing,
testing and improving this application.
#
(#how-it-works-526)
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.
5.
Please review
the guidelines for submitting to the Cookbook
cookbook)
to ensure consistency.
#
(#translations-527)
Translations
Email John David Anderson (docs at cakephp dot org) or on IRC (#cakephp on freenode as _psychic_) to discuss any translation
eforts you would like to participate in.
Translator tips:
Do not use
html entities
for accented
characters, the book uses UTF-8.
Use
Informal Form
.
Translate both the content and the title at the same time.
Browse and edit in the language the content is being translated to - otherwise it get's logged as an English Edit with only a
slim chance that a reviewer knows what language you are writing in.
Don't significantly change the markup or add new content - If the original content is missing some info, submit an edit for
that first.
If you need to write an English term, wrap it in
<em>
tags. E.g. "asdf asdf Controller asdf" or "asdf asdf Kontroller (Controller)
asfd" as appropriate.
We're committed to making the documentation for CakePHP better than it has ever been. We hope you'll join us by using the
Cookbook and giving back to a project that we've all benefited so much from.
1
(#beginning-with-cakephp-4)
Beginning With CakePHP
Welcome to the Cookbook, the manual for the CakePHP web application framework that makes developing a piece of cake!
This manual assumes that you have a general understanding of PHP and a basic understanding of object-oriented programming
(OOP). Diferent functionality within the framework makes use of diferent technologies — such as SQL, JavaScript, and XML — and
this manual does not attempt to explain those technologies, only how they are used in context.
1.1
(#what-is-cakephp-why-use-it-8)
What is CakePHP? Why Use it?
CakePHP
is a
free
,
open-source
/wiki/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
(https://trac.cakephp.org/wiki/Contributors)
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.
1 of 183
8/1/08 9:54 AM
Cookbook :: 1.2 Collection :: The Manual
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
sca
f
olding
f
old_%28programming%29)
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
1.2
(#where-to-get-help-9)
Where to Get Help
1.2.1 (#the-cookbook-552)
The Cookbook
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.
1.2.2
(#the-api-553)
The API
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.
1.2.3 (#the-irc-channel-554)
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.
1.2.4
(#the-bakery-555)
The Bakery
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.
1.2.5 (#cakeforge-556)
CakeForge
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.
1.2.6
(#the-oicial-cakephp-website-557)
The Oicial CakePHP website
The Oicial CakePHP website is always a great place to visit. It features links to oft-used developer tools, screencasts, donation
opportunities, and downloads.
1.2.7
(#the-google-group-558)
The Google Group
2 of 183
8/1/08 9:54 AM
Cookbook :: 1.2 Collection :: The Manual
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.
1.3
(#understanding-model-view-contr-10)
Understanding Model-View-Controller
1.3.1 (#overview-11)
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: 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.
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.
1.3.2
(#benefits-12)
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
/wiki/Software_prototyping)
. Separation also allows developers to make changes in one part of the application without afecting
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.
2
(#basic-principles-of-cakephp-13)
Basic Principles of CakePHP
The Start of Becoming a Smart Cookie
2.1
(#cakephp-structure-14)
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.
3 of 183
8/1/08 9:54 AM
Cookbook :: 1.2 Collection :: The Manual
2.1.1
(#controller-extensions-15)
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 diference 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.
2.1.2 (#view-extensions-16)
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.
2.1.3
(#model-extensions-17)
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
diferent 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 diferent 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. You can find the details in the models
chapter.
2.1.4 (#application-extensions-18)
Application Extensions
Controllers, helpers and models each 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 classes or files, 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
accomplishes a specific purpose that can span multiple applications. A user management system or a simplified blog might be a
good fit for CakePHP plugins.
2.2
(#a-typical-cakephp-request-21)
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.
4 of 183
8/1/08 9:54 AM
Cookbook :: 1.2 Collection :: The Manual
Figure 2. Typical Cake Request.
Black = required element, Gray = optional element, Blue = callback
1.
2.
The Router parses the URL in order to extract the parameters for this request: the controller, action, and any other
arguments that will afect 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 suiciently, 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.
2.3
(#cakephp-file-structure-19)
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.
2.3.1
(#the-app-folder-20)
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.
5 of 183
8/1/08 9:54 AM
[ Pobierz całość w formacie PDF ]