Let me know what you think of it. Looks really good. One thing I do recommend is learn how to use scaffolding, baking and the schema shell. I knew of their existence forever. I tried them briefly before. But only with my latest project a couple of weeks ago I truly spent time with these tools. Result: my mind blown away! Skip to content Home Archives About Contact me. Here are some of my favorite: PHP5 support. Lazy class loading. Previous versions of CakePHP could easily get slow with a lot of models.
There were solutions like Containable behavior and others. Enjoys exploring new stuff and possibilities, using new technologies and just having fun developing awesome stuff. I am glad to see that great CakePHP has reached the new version. Plenty of new features is mentioned. I can not wait to have a new project and build it in CakePHP. I have started using CakePHP 2. View all posts. I just hope that it will be faster then before. Nice post, BTW.
Read more. Interview with Jeffrey Way. Tags about ajax android api Basics blogging book cache cakephp cms codeforest croatia CSS css3 ghost giveaway google html5 javascript jquery jquery mobile json laravel mobile mysql mythbusters oop open source php plugins resources security services snippets Tips top twitter ux wamp web windows wordpress xmlrpc zend framework zend framework 2. CakeRequest::domain Returns the domain name your application is running on.
CakeRequest::subdomains Returns the subdomains your application is running on as an array. CakeRequest::host Returns the host your application is on. CakeRequest::referer Returns the referring address for the request. Additional parameters for the decoding function can be passed as arguments to input. Uses the built-in detection rules as well as any additional rules dened with CakeRequest::addDetector.
See Inspecting the request for more information. You can use CakeRequest::data to read this property in a way that suppresses notice errors. It encapsulates a number of features and functionality for generating HTTP responses in your application. The old methods are deprecated in favour of using CakeResponse. CakeResponse provides an interface to wrap the common response related tasks such as: Sending headers for redirects. Sending content type headers. Sending any header.
Sending the response body. CakeResponse is a exible and transparent to use class. But if you need to replace it with an application specic class, you can override and replace CakeResponse with your own class. By replacing the CakeResponse used in index. This will make all the controllers in your application use CustomResponse instead of CakeResponse.
Overriding the response object is handy during testing, as it allows you to stub out the methods that interact with header. See the section on CakeResponse and testing for more information. Dealing with content types You can control the Content-Type of your applications responses with using CakeResponse::type. Usually youll want to map additional content types in your controllers beforeFilter callback, so you can leverage the automatic view switching features of RequestHandlerComponent if you are using it.
Sending attachments There are times when you want to send Controller responses as les for download. You can either accomplish this using Media Views or by using the features of CakeResponse.
The above shows how you could use CakeResponse to generate a le download response without using MediaView. In general you will want to use MediaView as it provides a few additional features above what CakeResponse does.
Setting headers Setting headers is done with the CakeResponse::header method. Setting the same header multiple times will result in overwriting the previous values, just like regular header calls. Headers are not sent when CakeResponse::header is called either. They are just buffered until the response is actually sent.
Interacting with browser caching You sometimes need to force browsers to not cache the results of a controller action. You can also tell clients that you want them to cache responses. The above would tell clients to cache the resulting response for 5 days, hopefully speeding up your visitors experience. Expires, and Max-age are set based on the second parameter. Cache-Control is set to public as well.
Under this caching model you are only required to help clients decide if they should use a cached copy of the response by setting a few headers such as modied time, response entity tag and others. Opposed to having to code the logic for caching and for invalidating refreshing it once the data has changed, HTTP uses two models, expiration and validation which usually are a lot simpler than having to manage the cache yourself.
Apart from using CakeResponse::cache you can also use many other methods to ne tune HTTP cache headers to take advantage of browser or reverse proxy caching. The Cache Control header. New in version 2. Used under the expiration model, this header contains multiple indicators which can change the way browsers or proxies use the cached content. CakeResponse class helps you set this header with some utility methods that will produce a nal valid Cache-Control header. First of them is CakeResponse::sharable method, which indicates whether a response in to be considered sharable across different users or clients or users.
This method actually controls the public or private part of this header. Setting a response as private indicates that all or part of it is intended for a single user.
To take advantage of shared caches it is needed to set the control directive as public Second parameter of this method is used to specify a max-age for the cache, which is the number of seconds after which the response is no longer considered fresh.
CakeResponse exposes separate methods for setting each of the components in the Cache-Control header. The Expiration header. This method also accepts a DateTime or any string that can be parsed by the DateTime class.
The Etag header. Cache validation in HTTP is often used when content is constantly changing, and asks the application to only generate the response contents if the cache is no longer fresh. Under this model, the client continues to store pages in the cache, but instead of using it directly, it asks the application every time whether the resources changed or not.
This is commonly used with static resources such as images and other assets. The Etag header called entity tag is string that uniquely identies the requested resource.
It is very much like the checksum of a le, caching will compare checksums to tell whether they match or not. Also under the HTTP cache validation model, you can set the Last-Modied header to indicate the date and time at which the resource was modied for the last time. Setting this header helps CakePHP respond to caching clients whether the response was modied or not based on the client cache.
In some cases you might want to serve different contents using the same url. This is often the case when you have a multilingual page or respond with different HTML according to the browser that is requesting the resource. CakeResponse and testing Probably one of the biggest wins from CakeResponse comes from how it makes testing controllers and components easier.
Instead of methods spread across several objects, you only have a single object to mock as controllers and components delegate to CakeResponse.
Additionally you can more easily run tests from the command line, as you can use mocks to avoid the headers sent errors that can come up from trying to set headers in CLI.
CakeResponse::header Allows you to directly set one or many headers to be sent with the response. CakeResponse::charset Sets the charset that will be used in the response. You can either use a known content type alias or the full content type name. CakeResponse::cache Allows you to set caching headers in the response. CakeResponse::disableCache Sets the headers to disable client caching for the response. In that case deletes any response contents and sends the Not Modied header.
CakeResponse::compress Turns on gzip compression for the request. CakeResponse::download Allows you to send the response as an attachment and set the lename. CakeResponse::statusCode Allows you to set the status code for the response. CakeResponse::body Set the content body for the response.
CakeResponse::send Once you are done creating a response, calling send will send all the set headers as well as the body. This is done automatically at the end of each request by Dispatcher 68 Chapter 6. Scaffolding Application scaffolding is a technique that allows a developer to dene and create a basic application that can create, retrieve, update and delete objects. Scaffolding in CakePHP also allows developers to dene how objects are related to each other, and to create and break those links.
All thats needed to create a scaffold is a model and its controller. CakePHPs scaffolding is pretty cool. It allows you to get a basic CRUD application up and going in minutes. Its so cool that youll want to use it in production apps. Now, we think its cool too, but please realize that scaffolding is Its a loose structure you throw up real quick during the beginning of a project in order to get started.
It isnt meant to be completely exible, its meant as a temporary way to get up and going. If you nd yourself really wanting to customize your logic and your views, its time to pull your scaffolding down in order to write some code. CakePHPs Bake console, covered in the next section, is a great next step: it generates all the code that would produce the same result as the most current scaffold.
Scaffolding is a great way of getting the early parts of developing a web application started. Early database schemas are subject to change, which is perfectly normal in the early part of the design process. This has a downside: a web developer hates creating forms that never will see real use. To reduce the strain on the developer, scaffolding has been included in CakePHP.
Scaffolding analyzes your database tables and creates standard lists with add, delete and edit buttons, standard forms for editing and standard views for inspecting a single item in the database. Note: Creating methods in controllers that are scaffolded can cause unwanted results. For example, if you create an index method in a scaffolded controller, your index method will be rendered rather than the scaffolding functionality.
Scaffolding is knowledgeable about model associations, so if your Category model belongsTo a User, youll see related User IDs in the Category listings. While scaffolding knows about model associations, you will not see any related records in the scaffold views until you manually add the association code to the model.
Before you add the following code, the view displays an empty select input for Group in the New User form. This is an easy way to create a simple backend interface quickly.
Keep in mind that you cannot have both admin and non-admin methods scaffolded at the same time. Once you have replaced a scaffolded action you will need to create a view le for the action as well. Customizing Scaffold Views If youre looking for something a little different in your scaffolded views, you can create templates.
We still dont recommend using this technique for production applications, but such a customization may be useful during prototyping iterations. This is a simple and optional controller for serving up static content. The home page you see after installation is generated using this controller. You are free to modify the Pages Controller to meet your needs. Changed in version 2. Since 2. Components Components are packages of logic that are shared between controllers.
If you nd yourself wanting to copy and paste things between controllers, you might consider wrapping some functionality in a component. Each of these core components are detailed in their own chapters. For now, well show you how to create your own components. Creating components keeps controller code clean and allows you to reuse code between projects. Conguring Components Many of the core components require conguration. Some examples of components requiring conguration are Authentication, Cookie and EmailComponent.
All core components allow their conguration settings to be set in this way. In addition you can congure components in your controllers beforeFilter method. This is useful when you need to assign the results of a function to a component property. Its possible, however, that a component requires certain conguration options to be set before the controllers beforeFilter is run.
Consult the relevant documentation to determine what conguration options each component provides. One common setting to use is the className option, which allows you to alias components. Note: Aliasing a component replaces that instance anywhere that component is used, including inside other Components.
Using Components Once youve included some components in your controller, using them is pretty simple. Each component you use is exposed as a property on your controller. Note: Since both Models and Components are added to Controllers as properties they share the same namespace. Be sure to not give a component and a model the same name. You might not need all of your components available on every controller action.
In situations like this you can load a component at runtime using the Component Collection. Component Callbacks Components also offer a few request life-cycle callbacks that allow them to augment the request cycle. See the base Component API for more information on the callbacks components offer. Creating a Component Suppose our online application needs to perform a complex mathematical operation in many different parts of the application.
We could create a component to house this shared logic for use in many different controllers. The rst step is to create a new component le and class.
Components declared in AppController will be merged with those in your other controllers. So there is no need to re-declare the same component twice.
When including Components in a Controller you can also declare a set of parameters that will be passed on to the Components constructor. By convention, any settings that have been passed that are also public properties on your component will have the values set based on the settings. Using other Components in your Component. Sometimes one of your components may need to use another component. Component API class Component The base Component class offers a few methods for lazily loading other Components through ComponentCollection as well as dealing with common handling of settings.
It also provides prototypes for all the component callbacks. If this method returns false the controller will not continue on to redirect the request. You can also return a string which will be interpreted as the url to redirect to or return associative array with key url and optionally status and exit.
Views are the V in MVC. Views are responsible for generating the specic output required for the request. To serve protected les, or dynamically generated les, you can use Media Views To create multiple themed views, you can use Themes. These les contain all the presentational logic needed to get the data it received from the controller in a format that is ready for the audience youre serving to. The view layer in CakePHP can be made up of a number of different parts.
Each part has different uses, and will be covered in this chapter: views: Views are the part of the page that is unique to the action being run. They form the meat of your applications response. Elements are usually rendered inside of views.
Most views are rendered inside of a layout. Extending Views New in version 2. View extending allows you to wrap one view in another. Combining this with view blocks gives you a powerful way to keep your views DRY. For example, your application has a sidebar that needs to change depending on the specic view being rendered. The above view le could be used as a parent view. It expects that the view extending it will dene the sidebar and title blocks. The content block is a special block that CakePHP creates.
It will contain all the un-captured content from the extending view. The post view above shows how you can extend a view, and populate a set of blocks. Any content not 78 Chapter 7. When a view contains a call to extend execution continues to the bottom of the current view le. Once its complete, the extended view will be rendered.
You can nest extended views as many times as necessary. Each view can extend another view if desired. Each parent view will get the previous views content as the content block. Note: You should avoid using content as a block name in your application. CakePHP uses this for un-captured content in extended views. Using view blocks New in version 2. Blocks can be dened in two ways. Either as a capturing block, or by direct assignment.
You can also append into a block using start multiple times. Note: You should avoid using content as a block name. This is used by CakePHP internally for extended views, and view content in the layout. Displaying blocks New in version 2. You can display blocks using the fetch method.
You can also use fetch to conditionally show content that should surround a block should it exist. Using blocks for script and CSS les New in version 2. Instead you should use blocks. Layouts A layout contains presentation code that wraps around a view. Anything you want to see in all of your views should be placed in a layout.
Once a new default layout has been created, controller-rendered view code is placed inside of the default layout when the page is rendered. When you create a layout, you need to tell CakePHP where to place the code for your views. Note: Prior to version 2. Useful for including javascript and CSS les from views. Note: When using HtmlHelper::css or HtmlHelper::script in view les, specify false for the inline option to place the html source in a block with the same name.
See API for more details on Layouts The content block contains the contents of the rendered view. The Ajax layout is handy for crafting Ajax responses - its an empty layout most ajax. The ash layout is used for messages shown by Controller::flash method.
Using layouts from plugins New in version 2. If you want to use a layout that exists in a plugin, you can use plugin syntax. Elements Many applications have small blocks of presentation code that need to be repeated from page to page, sometimes in different places in the layout. CakePHP can help you repeat parts of your website that need to be reused. These reusable parts are called Elements. Ads, help boxes, navigational controls, extra menus, login forms, and callouts are often implemented in CakePHP as elements.
An element is basically a miniview that can be included in other views, in layouts, and even within other elements. Elements can be used to make a view more readable, placing the rendering of repeating elements in its own le. They can also help you re-use content fragments in your application. Inside the element le, all the passed variables are available as members of the parameter array in the same way that Controller::set in the controller works with view les.
The View::element method also supports options for the element. The options supported are cache and callbacks. An example:. Element caching is facilitated through the Cache class. You can congure elements to be stored in any Cache conguration youve setup. This gives you a great amount of exibility to decide where and for how long elements are stored. You can take full advantage of elements by using requestAction. The requestAction function fetches view variables from a controller action and returns them as an array.
This enables your elements to perform in true MVC style. Create a controller action that prepares the view variables for your elements, then call requestAction inside the second parameter of element to feed the element the view variables from your controller. And then in the element we can access the paginated posts model.
If set to true, it will cache the element in the default Cache conguration. Otherwise, you can set which cache conguration should be used. See Caching for more information on conguring Cache. If you render the same element more than once in a view and have caching enabled be sure to set the key parameter to a different name each time. This will prevent each successive call from overwriting the previous element calls cached result.
The above will ensure that both element results are cached separately. CakePHP will use this conguration, when none is given. Requesting Elements from a Plugin 2.
If the element doesnt exist in the plugin, it will look in the main APP folder. If your view is a part of a plugin you can omit the plugin name. Are equivalent and will result in the same element being rendered. Using set from your view le will add the variables to the layout and elements that will be rendered later.
See Controller Methods for more information on using set. Returns an array of variable names. See the section on Elements for more information and examples. This method is helpful when creating helpers that need to add javascript or css directly to the layout. Deprecated since version 2. View::blocks Get the names of all dened blocks as an array. See the section on Using view blocks for examples. View::end End the top most open capturing block. This will overwrite any existing content.
Will be returned for blocks that are not dened. See the section on Extending Views for examples. Setting this property will change the default conguration used to cache elements. This default can be overridden using the cache option in the element method.
Use this instance to access information about the current request. Used to provide view block functionality in view rendering. More about Views Themes You can take advantage of themes, making it easy to switch the look and feel of your page quickly and easily. Within the themed folder, create a folder using the same name as your theme name. This way, you can create master view les and simply override them on a case-by-case basis within your theme folder.
Theme assets Themes can contain static assets as well as view les. A theme can include any necessary assets in its webroot directory. This allows for easy packaging and distribution of themes. While in development, requests for theme assets will be handled by Dispatcher.
To improve performance for production environments, its recommended that you either symlink or copy theme assets into the applications webroot. See below for more information. The Dispatcher will handle nding the correct theme assets in your view paths.
All of CakePHPs built-in helpers are aware of themes and will create the correct paths automatically. Increasing performance of plugin and theme assets Its a well known fact that serving assets through PHP is guaranteed to be slower than serving those assets without invoking PHP. And while the core team has taken steps to make plugin and theme asset serving as fast as possible, there may be situations where more performance is required.
Media Views class MediaView Media views allow you to send binary les to the user. For example, you may wish to have a directory of les outside of the webroot to prevent users from direct linking them. To use the Media view, you need to tell your controller to use the MediaView class instead of the default View class.
Settable Parameters id The ID is the le name as it resides on the le server including the le extension. Specify the name without the le extension. This is matched against an internal list of acceptable mime types.
If the mime type specied is not in the list or sent in the mimeType parameter array , the le will not be downloaded. By enabling RequestHandlerComponent in your application, and enabling support for the xml and or json extensions, you can automatically leverage the new view classes. XmlView and JsonView will be referred to as data views for the rest of this page. There are two ways you can generate data views. Enabling data views in your application Before you can use the data view classes, youll need to do a bit of setup: 1.
Enable the json and or xml extensions with Router::parseExtensions. This will enable Router to handle mulitple extensions. Add the RequestHandlerComponent to your controllers list of components.
This will enable automatic view class switching on content types. After adding Router::parseExtensions json ; to your routes le, CakePHP will automatically switch view classes when a request is done with the. If you need to do any formatting or manipulation of your view variables before generating the response, you should use view les.
Without a single top-level element the Xml will fail to generate. Using a data view with view les You should use view les if you need to do some manipulation of your view content before creating the nal output. You can do more more complex manipulations, or use helpers to do formatting as well. Note: The data view classes dont support layouts. They assume that the view le will output the serialized content.
See above for how you can use JsonView in your application. Helpers Helpers are the component-like classes for the presentation layer of your application. They contain presentational logic that is shared between many views, elements, or layouts. This chapter will show you how to create your own helpers, and outline the basic tasks CakePHPs core helpers can help you accomplish.
CakePHP features a number of helpers that aid in view creation. They assist in creating well-formed markup including forms , aid in formatting text, times and numbers, and can even speed up Ajax functionality. You can also add helpers from within an action, so they will only be available to that action and not the other actions in the controller. You can pass options to helpers. One common setting to use is the className option, which allows you to create aliased helpers in your views.
Note: Aliasing a helper replaces that instance anywhere that helper is used, including inside other Helpers. Using helper settings allows you to declaratively congure your helpers and keep conguration logic out of your controller actions.
Using Helpers Once youve congured which helpers you want to use in your controller, each helper is exposed as a public property in the view. The above would call the css method on the HtmlHelper. There may come a time where you need to dynamically load a helper from inside a view. You can use the views HelperCollection to do this:.
Callback methods Helpers feature several callbacks that allow you to augment the view rendering process. Creating Helpers If a core helper or one showcased on github or the Bakery doesnt t your needs, helpers are easy to create. Lets say we wanted to create a helper that could be used to output a specically crafted CSS-styled link you needed many different places in your application.
Lets call our helper LinkHelper. You may wish to use some functionality already existing in another helper. It provides a number of utility methods and features for loading other helpers. If a theme is active and the le exists in the current themes webroot, the path to the themed le will be returned. This includes elements, views, parent views, and layouts. Receives the le being rendered as an argument. Receives the layout lename as an argument.
Core Helpers CacheHelper Used by the core to cache view content. HtmlHelper Convenience methods for crafting well-formed markup. Images, links, tables, header tags and more. JsHelper Used to create Javascript compatible with various Javascript libraries.
NumberHelper Number and currency formatting. Paginator Model data pagination and sorting. SessionHelper Access for reading session values in views. TextHelper Smart linking, highlighting, word smart truncation. TimeHelper Proximity detection is this next year? Models are the classes that sit as the business layer in your application.
This means that they should be responsible for managing almost everything that happens regarding your data, its validity, interactions and evolution of the information workow in your domain of work. Usually model classes represent data and are used in CakePHP applications for data access, more specically they represent a database table but they are not limited to this, but can be used to access anything that manipulates data such as les, external web services, iCal events, or rows in a CSV le.
A model can be associated with other models. For example, a Recipe may be associated with the Author of the recipe as well as the Ingredient in the recipe. This section will explain what features of the model can be automated, how to override those features, and what methods and properties a model can have.
Itll explain the different ways to associate your data. Itll describe how to nd, save, and delete data. Finally, itll look at Datasources. Understanding Models A Model represents your data model. In object-oriented programming a data model is an object that represents a thing, like a car, a person, or a house. A blog, for example, may have many blog posts and each blog post may have many comments. The Blog, Post, and Comment are all examples of models, each associated with another.
With just this simple declaration, the Ingredient model is bestowed with all the functionality you need to create queries along with saving and deleting data. The Ingredient model extends the application model, AppModel, which.
It is this core Model class that bestows the functionality onto your Ingredient model. This intermediate class, AppModel, is empty and if you havent created your own, is taken from within the CakePHP core folder. Overriding the AppModel allows you to dene functionality that should be made available to all models within your application. To do so, you need to create your own AppModel. Creating a project using Bake will automatically generate this le for you. See also Behaviors for more information on how to apply similar logic to multiple models.
By convention it should have the same name as the class; for this example Ingredient. This also means that if your model le isnt named correctly i. If youre trying to use a method youve dened in your model, or a behavior attached to your model and youre getting SQL errors that are the name of the method youre calling - its a sure sign CakePHP cant nd your model and you either need to check the le names, your application cache, or both.
Note: Some class names are not usable for model names. With your model dened, it can be accessed from within your Controller.
CakePHP will automatically make the model available for access when its name matches that of the controller. Associated models are available through the main model.
0コメント