Docsity

Cake PHP Cookbook PDF, Study notes of Computer Programming

Partial preview of the text

Download Cake PHP Cookbook PDF and more Study notes Computer Programming in PDF only on Docsity!

CakePHP Cookbook Documentation

Release 2.x

Cake Software Foundation

August 05, 2014

  • 1 Getting Started
  • 2 Blog Tutorial
    • Getting CakePHP
    • Creating the Blog Database
    • CakePHP Database Configuration
    • Optional Configuration
    • A Note on mod_rewrite
  • 3 Blog Tutorial - Adding a layer
    • Create a Post Model
    • Create a Posts Controller
    • Creating Post Views
    • Adding Posts
    • Data Validation
    • Editing Posts
    • Deleting Posts
    • Routes
    • Conclusion
    • Additional Reading
  • 4 Installation
    • Requirements
    • License
    • Downloading CakePHP
    • Permissions
    • Setup
    • Development
    • Production
    • Advanced Installation and URL Rewriting
    • Fire It Up
  • 5 CakePHP Overview
    • What is CakePHP? Why use it?
    • Understanding Model-View-Controller
    • Where to Get Help
  • 6 Controllers
    • The App Controller
    • Request parameters
    • Controller actions
    • Request Life-cycle callbacks
    • Controller Methods
    • Controller Attributes
    • More on controllers
  • 7 Views
    • View Templates
    • Using view blocks
    • Layouts
    • Elements
    • Creating your own view classes
    • View API
    • More about Views
  • 8 Models
    • Understanding Models
    • More on models
  • 9 Core Libraries
    • General Purpose
    • Behaviors
    • Components
    • Helpers
    • Utilities
  • 10 Plugins
    • Installing a Plugin
    • Plugin configuration
    • Advanced bootstrapping
    • Using a Plugin
    • Creating Your Own Plugins
    • Plugin Controllers
    • Plugin Models
    • Plugin Views
    • Plugin assets
    • Components, Helpers and Behaviors
    • Expand Your Plugin
    • Plugin Tips
  • 11 Console and Shells
    • The CakePHP console
    • Creating a shell
    • Shell tasks
    • Invoking other shells from your shell
    • Console output levels
    • Styling output
    • Configuring options and generating help
    • Routing in shells / CLI
    • Shell API
    • More topics
  • 12 Development
    • Configuration
    • Routing
    • Sessions
    • Exceptions
    • Error Handling
    • Debugging
    • Testing
    • REST
    • Dispatcher Filters
    • Vendor packages
  • 13 Deployment
    • Check your security
    • Set document root
    • Update core.php
    • Improve your application’s performance
  • 14 Tutorials & Examples
    • Blog Tutorial
    • Blog Tutorial - Adding a layer
    • Simple Authentication and Authorization Application
    • Simple Acl controlled Application
    • Simple Acl controlled Application - part
  • 15 Appendices
    • 2.5 Migration Guide
    • 2.4 Migration Guide
    • 2.3 Migration Guide
    • 2.2 Migration Guide
    • 2.1 Migration Guide
    • 2.0 Migration Guide
    • Migration from 1.2 to 1.3
    • General Information
  • 16 Indices and tables

CHAPTER 1

Getting Started

The CakePHP framework provides a robust base for your application. It can handle every aspect, from the user’s initial request all the way to the final rendering of a web page. And since the framework follows the principles of MVC, it allows you to easily customize and extend most aspects of your application.

The framework also provides a basic organizational structure, from filenames to database table names, keep- ing your entire application consistent and logical. This concept is simple but powerful. Follow the conven- tions and you’ll always know exactly where things are and how they’re organized.

The best way to experience and learn CakePHP is to sit down and build something. To start off we’ll build a simple blog application.

CakePHP Cookbook Documentation, Release 2.x

2 Chapter 1. Getting Started

CakePHP Cookbook Documentation, Release 2.x

You can also clone the repository using git^1. git clone git://github.com/cakephp/cakephp.git

Regardless of how you downloaded it, place the code inside of your DocumentRoot. Once finished, your directory setup should look something like the following:

/path_to_document_root /app /lib /plugins /vendors .htaccess index.php README

Now might be a good time to learn a bit about how CakePHP’s directory structure works: check out the CakePHP Folder Structure section.

Tmp directory permissions

Next we’ll need to make the app/tmp directory writable by the webserver. The best way to do this is to find out what user your webserver runs as. You can run inside any PHP file your webserver can execute. You should see a username printed. Change the ownership of the app/tmp directory to that user. The final command you run (in *nix) might look something like this:

$ chown -R www-data app/tmp

If for some reason CakePHP can’t write to that directory, you’ll see warnings and uncaught exceptions that cache data cannot be written.

Creating the Blog Database

Next, let’s set up the underlying database for our blog. If you haven’t already done so, create an empty database for use in this tutorial, with a name of your choice. Right now, we’ll just create a single table to store our posts. We’ll also throw in a few posts right now to use for testing purposes. Execute the following SQL statements into your database:

/* First, create our posts table: (^) */ CREATE TABLE posts ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(50), body TEXT, created DATETIME DEFAULT NULL , modified DATETIME DEFAULT NULL );

/* Then insert some posts for testing: (^) */ INSERT INTO posts (title,body,created) VALUES (’The title’, ’This is the post body.’, NOW()); (^1) http://git-scm.com/

4 Chapter 2. Blog Tutorial

CakePHP Cookbook Documentation, Release 2.x

INSERT INTO posts (title,body,created) VALUES (’A title once again’, ’And the post body follows.’, NOW()); INSERT INTO posts (title,body,created) VALUES (’Title strikes back’, ’This is really exciting! Not.’, NOW());

The choices on table and column names are not arbitrary. If you follow CakePHP’s database naming con- ventions, and CakePHP’s class naming conventions (both outlined in CakePHP Conventions), you’ll be able to take advantage of a lot of free functionality and avoid configuration. CakePHP is flexible enough to accommodate even the worst legacy database schema, but adhering to convention will save you time.

Check out CakePHP Conventions for more information, but suffice it to say that naming our table ‘posts’ automatically hooks it to our Post model, and having fields called ‘modified’ and ‘created’ will be automag- ically managed by CakePHP.

CakePHP Database Configuration

Onward and upward: let’s tell CakePHP where our database is and how to connect to it. For many, this is the first and last time you configure anything.

A copy of CakePHP’s database configuration file is found in /app/Config/database.php.default. Make a copy of this file in the same directory, but name it database.php.

The config file should be pretty straightforward: just replace the values in the $default array with those that apply to your setup. A sample completed configuration array might look something like the following:

public $default = array ( ’datasource’ => ’Database/Mysql’, ’persistent’ => false , ’host’ => ’localhost’, ’port’ => ’’, ’login’ => ’cakeBlog’, ’password’ => ’c4k3-rUl3Z’, ’database’ => ’cake_blog_tutorial’, ’schema’ => ’’, ’prefix’ => ’’, ’encoding’ => ’utf8’ );

Once you’ve saved your new database.php file, you should be able to open your browser and see the CakePHP welcome page. It should also tell you that your database connection file was found, and that CakePHP can successfully connect to the database.

Note: Remember that you’ll need to have PDO, and pdo_mysql enabled in your php.ini.

CakePHP Database Configuration 5

CakePHP Cookbook Documentation, Release 2.x

First, we configure the "default" to be a very restrictive set of

features.

Options FollowSymLinks AllowOverride All

Order deny,allow

Deny from all

  1. Make sure you are loading mod_rewrite correctly. You should see something like: LoadModule rewrite_module libexec/apache2/mod_rewrite.so

In many systems these will be commented out by default, so you may just need to remove the leading

symbols.

After you make changes, restart Apache to make sure the settings are active. Verify that your .htaccess files are actually in the right directories. Some operating systems treat files that start with ‘.’ as hidden and therefore won’t copy them.

  1. Make sure your copy of CakePHP comes from the downloads section of the site or our Git repository, and has been unpacked correctly, by checking for .htaccess files. CakePHP root directory (must be copied to your document; redirects everything to your CakePHP app):

    RewriteEngine on RewriteRule ^ $ app/webroot/ [L] RewriteRule (.*) app/webroot/ $ 1 [L]

CakePHP app directory (will be copied to the top directory of your application by bake):

RewriteEngine on RewriteRule ^ $ webroot/ [L] RewriteRule (.*) webroot/ $ 1 [L]

CakePHP webroot directory (will be copied to your application’s web root by bake):

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*) $ index.php [QSA,L]

If your CakePHP site still has problems with mod_rewrite, you might want to try modifying settings for Virtual Hosts. On Ubuntu, edit the file /etc/apache2/sites-available/default (location is distribution- dependent). In this file, ensure that AllowOverride None is changed to AllowOverride

A Note on mod_rewrite 7

CakePHP Cookbook Documentation, Release 2.x

All, so you have:

Options FollowSymLinks AllowOverride All

Options Indexes FollowSymLinks MultiViews AllowOverride All Order Allow,Deny Allow from all

On Mac OSX, another solution is to use the tool virtualhostx^2 to make a Virtual Host to point to your folder. For many hosting services (GoDaddy, 1and1), your web server is actually being served from a user directory that already uses mod_rewrite. If you are installing CakePHP into a user direc- tory (http://example.com/~username/cakephp/), or any other URL structure that already utilizes mod_rewrite, you’ll need to add RewriteBase statements to the .htaccess files CakePHP uses (/.htac- cess, /app/.htaccess, /app/webroot/.htaccess). This can be added to the same section with the RewriteEngine directive, so for example, your webroot .htaccess file would look like:

RewriteEngine On RewriteBase /path/to/cake/app RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*) $ index.php [QSA,L]

The details of those changes will depend on your setup, and can include additional things that are not related to CakePHP. Please refer to Apache’s online documentation for more information.

  1. (Optional) To improve production setup, you should prevent invalid assets from being parsed by CakePHP. Modify your webroot .htaccess to something like:

    RewriteEngine On RewriteBase /path/to/cake/app RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !^/(app/webroot/)?(img|css|js)/(.*) $ RewriteRule ^(.*) $ index.php [QSA,L]

The above will simply prevent incorrect assets from being sent to index.php and instead display your webserver’s 404 page. Additionally you can create a matching HTML 404 page, or use the default built-in CakePHP 404 by adding an ErrorDocument directive: (^2) http://clickontyler.com/virtualhostx/

8 Chapter 2. Blog Tutorial

CakePHP Cookbook Documentation, Release 2.x

  1. Create a new file called web.config in your CakePHP root folder.
  2. Using Notepad or any XML-safe editor, copy the following code into your new web.config file...

Once the web.config file is created with the correct IIS-friendly rewrite rules, CakePHP’s links, CSS, JavaS- cipt, and rerouting should work correctly.

URL-Rewriting on lighttpd

Lighttpd does not support .htaccess functions, so you can remove all .htaccess files. In the lighttpd configu- ration, make sure you’ve activated “mod_rewrite”. Add a line:

url.rewrite- if - not -file =( "^([^?]*)(?(.+))?$" => "/index.php?url=$1&$3" )

URL rewrite rules for Hiawatha

The required UrlToolkit rule (for URL rewriting) to use CakePHP with Hiawatha is:

10 Chapter 2. Blog Tutorial

CakePHP Cookbook Documentation, Release 2.x

UrlToolkit { ToolkitID = cakephp RequestURI exists Return Match .* Rewrite /index.php }

I don’t / can’t use URL rewriting

If you don’t want to or can’t use URL rewriting on your webserver, refer to the core configuration.

Now continue to Blog Tutorial - Adding a layer to start building your first CakePHP application.

A Note on mod_rewrite 11

CHAPTER 3

Blog Tutorial - Adding a layer

Create a Post Model

The Model class is the bread and butter of CakePHP applications. By creating a CakePHP model that will interact with our database, we’ll have the foundation in place needed to do our view, add, edit, and delete operations later.

CakePHP’s model class files go in /app/Model, and the file we’ll be creating will be saved to /app/Model/Post.php. The completed file should look like this:

class Post extends AppModel { }

Naming conventions are very important in CakePHP. By naming our model Post, CakePHP can automat- ically infer that this model will be used in the PostsController, and will be tied to a database table called posts.

Note: CakePHP will dynamically create a model object for you if it cannot find a corresponding file in /app/Model. This also means that if you accidentally name your file wrong (for example, post.php or posts.php instead of Post.php), CakePHP will not recognize any of your settings and will use the defaults instead.

For more on models, such as table prefixes, callbacks, and validation, check out the Models chapter of the Manual.

Create a Posts Controller

Next, we’ll create a controller for our posts. The controller is where all the business logic for post interaction will happen. In a nutshell, it’s the place where you play with the models and get post-related work done. We’ll place this new controller in a file called PostsController.php inside the /app/Controller directory. Here’s what the basic controller should look like:

CakePHP Cookbook Documentation, Release 2.x

class PostsController extends AppController { public $helpers = array (’Html’, ’Form’); }

Now, let’s add an action to our controller. Actions often represent a single function or interface in an application. For example, when users request www.example.com/posts/index (which is the same as www.example.com/posts/), they might expect to see a listing of posts. The code for that action would look something like this:

class PostsController extends AppController { public $helpers = array (’Html’, ’Form’);

public function index() { $this->set(’posts’, $this->Post->find(’all’)); } }

By defining function index() in our PostsController, users can access the logic there by requesting www.example.com/posts/index. Similarly, if we were to define a function called foobar(), users would be able to access that at www.example.com/posts/foobar.

Warning: You may be tempted to name your controllers and actions a certain way to obtain a certain URL. Resist that temptation. Follow CakePHP conventions (capitalization, plural names, etc.) and create readable, understandable action names. You can map URLs to your code using “routes” covered later on.

The single instruction in the action uses set() to pass data from the controller to the view (which we’ll create next). The line sets the view variable called ‘posts’ equal to the return value of the find(’all’) method of the Post model. Our Post model is automatically available at $this->Post because we’ve followed CakePHP’s naming conventions.

To learn more about CakePHP’s controllers, check out the Controllers chapter.

Creating Post Views

Now that we have our data flowing to our model, and our application logic and flow defined by our controller, let’s create a view for the index action we created above.

CakePHP views are just presentation-flavored fragments that fit inside an application’s layout. For most applications, they’re HTML mixed with PHP, but they may end up as XML, CSV, or even binary data.

A layout is presentation code that is wrapped around a view. Multiple layouts can be defined, and you can switch between them, but for now, let’s just use the default.

Remember how in the last section we assigned the ‘posts’ variable to the view using the set() method? That would pass data to the view that would look something like this:

// print_r($posts) output:

Array

14 Chapter 3. Blog Tutorial - Adding a layer