Getting Started — CakePHP Cookbook v2

download Getting Started — CakePHP Cookbook v2

of 18

Transcript of Getting Started — CakePHP Cookbook v2

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    1/18

    ookbook2.x 2.x Book en

    Getting Started

    The CakePHP framework provides a robust base for your application. It can handle

    every aspect, from the users initial request all the way to the final rendering of a w

    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, keeping your entire application consistent and logical. Thisconcept is simple but powerful. Follow the conventions and youll always know exac

    where things are and how theyre organized.

    The best way to experience and learn CakePHP is to sit down and build something

    start off well build a simple blog application.

    Blog Tutorial

    Welcome to CakePHP. Youre probably checking out this tutorial because you wan

    learn more about how CakePHP works. Its our aim to increase productivity and macoding more enjoyable: we hope youll see this as you dive into the code.

    This tutorial will walk you through the creation of a simple blog application. Well be

    getting and installing CakePHP, creating and configuring a database, and creating

    enough application logic to list, add, edit, and delete blog posts.

    Heres what youll need:

    1. A running web server. Were going to assume youre using Apache, though th

    instructions for using other servers should be very similar. We might have to pa little with the server configuration, but most folks can get CakePHP up and

    running without any configuration at all. Make sure you have PHP 5.2.8 or

    greater.

    2. A database server. Were going to be using MySQL server in this tutorial. You

    need to know enough about SQL in order to create a database: CakePHP will

    taking the reins from there. Since were using MySQL, also make sure that yo

    have pdo_mysqlenabled in PHP.

    3. Basic PHP knowledge. The more object-oriented programming youve done, t

    better: but fear not if youre a procedural fan.

    Welcome

    nstallation

    etting Started

    log Tutorial

    URL Rewriting

    log Tutorial - Adding

    layer

    ATypical CakePHP

    Request

    CakePHP

    Conventions

    CakePHP Folder

    Structure

    CakePHP Structure

    akePHP Overview

    ontrollersiews

    odels

    ore Libraries

    ugins

    onsole and Shells

    evelopment

    eployment

    utorials & Examplesontributing

    ppendices

    Page

    ontents

    etting Started

    log Tutorial

    Getting CakePHP

    Search

    CakePHP Downloads Documentation Community Services

    http://book.cakephp.org/2.0/en/contributing.htmlhttp://community.cakephp.org/http://cakephp.org/serviceshttp://book.cakephp.org/2.0/en/plugins.htmlhttp://book.cakephp.org/2.0/en/core-libraries.htmlhttp://book.cakephp.org/2.0/en/controllers.htmlhttp://book.cakephp.org/2.0/en/cakephp-overview.htmlhttp://book.cakephp.org/2.0/en/getting-started/cakephp-structure.htmlhttp://book.cakephp.org/2.0/en/getting-started/cakephp-folder-structure.htmlhttp://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.htmlhttp://book.cakephp.org/2.0/en/getting-started/a-typical-cakephp-request.htmlhttp://book.cakephp.org/2.0/en/getting-started/a-typical-cakephp-request.htmlhttp://book.cakephp.org/2.0/en/installation/url-rewriting.htmlhttp://book.cakephp.org/2.0/en/index.htmlhttp://book.cakephp.org/2.0/en/contents.htmlhttp://book.cakephp.org/2.0/en/contents.htmlhttp://book.cakephp.org/2.0/en/contents.htmlhttp://cakephp.org/serviceshttp://community.cakephp.org/http://cakephp.org/http://book.cakephp.org/2.0/en/contents.htmlhttp://book.cakephp.org/2.0/en/appendices.htmlhttp://book.cakephp.org/2.0/en/contributing.htmlhttp://book.cakephp.org/2.0/en/tutorials-and-examples.htmlhttp://book.cakephp.org/2.0/en/deployment.htmlhttp://book.cakephp.org/2.0/en/development.htmlhttp://book.cakephp.org/2.0/en/console-and-shells.htmlhttp://book.cakephp.org/2.0/en/plugins.htmlhttp://book.cakephp.org/2.0/en/core-libraries.htmlhttp://book.cakephp.org/2.0/en/models.htmlhttp://book.cakephp.org/2.0/en/views.htmlhttp://book.cakephp.org/2.0/en/controllers.htmlhttp://book.cakephp.org/2.0/en/cakephp-overview.htmlhttp://book.cakephp.org/2.0/en/getting-started/cakephp-structure.htmlhttp://book.cakephp.org/2.0/en/getting-started/cakephp-folder-structure.htmlhttp://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.htmlhttp://book.cakephp.org/2.0/en/getting-started/a-typical-cakephp-request.htmlhttp://book.cakephp.org/2.0/en/installation/url-rewriting.htmlhttp://book.cakephp.org/2.0/en/getting-started.htmlhttp://book.cakephp.org/2.0/en/installation.htmlhttp://book.cakephp.org/2.0/en/index.htmlhttp://book.cakephp.org/2.0/en/contents.html
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    2/18

    4. Finally, youll need a basic knowledge of the MVC programming pattern. A qu

    overview can be found in Understanding Model-View-Controller. Dont worry,

    only a half a page or so.

    Lets get started!

    Getting CakePHPFirst, lets get a copy of fresh CakePHP code.

    To get a fresh download, visit the CakePHP project on GitHub:

    https://github.com/cakephp/cakephp/tags (https://github.com/cakephp/cakephp/tag

    and download the latest release of 2.0

    You can also clone the repository using git (http://git-scm.com/). git clone

    git://github.com/cakephp/cakephp.git

    Regardless of how you downloaded it, place the code inside of your DocumentRoo

    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 CakePHPs directory structure

    works: check out the CakePHP Folder Structure(getting-started/cakephp-folder-structure.html)section.

    Tmp directory permissions

    Next well need to make the app/tmpdirectory writable by the webserver. The bes

    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

    a username printed. Change the ownership of the app/tmpdirectory to that user.

    final command you run (in *nix) might look something like this:

    $ chown -R www-data app/tmp

    If for some reason CakePHP cant write to that directory, youll see warnings and

    uncaught exceptions that cache data cannot be written.

    Creating the Blog Database

    Tmp directory

    permissions

    Creating the Blog

    Database

    CakePHP Database

    Configuration

    Optional

    Configuration

    A Note on

    mod_rewrite

    log Tutorial - Adding

    layer

    Create a Post Model

    Create a Posts

    Controller

    Creating Post Views

    Adding Posts

    Data Validation

    Editing Posts

    Deleting Posts

    Routes

    Conclusion

    Suggested

    Follow-up

    ReadingAdditional Reading

    http://book.cakephp.org/2.0/en/getting-started/cakephp-folder-structure.htmlhttp://git-scm.com/https://github.com/cakephp/cakephp/tagshttp://book.cakephp.org/2.0/en/cakephp-overview/understanding-model-view-controller.html
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    3/18

    Next, lets set up the underlying database for our blog. If you havent already done

    create an empty database for use in this tutorial, with a name of your choice. Right

    now, well just create a single table to store our posts. Well also throw in a few pos

    right now to use for testing purposes. Execute the following SQL statements into yo

    database:

    /* First, create our posts table: */CREATE TABLE posts ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(50), body TEXT, created DATETIMEDEFAULTNULL, modified DATETIMEDEFAULTNULL);

    /* Then insert some posts for testing: */INSERT INTO posts (title,body,created) VALUES ('The title', 'This is the post body.', NOW());INSERT INTO posts (title,body,created) VALUES ('A title once again', 'And the post body follows.', INSERT INTO posts (title,body,created) VALUES ('Title strikes back', 'This is really exciting! Not

    The choices on table and column names are not arbitrary. If you follow CakePHPs

    database naming conventions, and CakePHPs class naming conventions (both

    outlined in CakePHP Conventions (getting-started/cakephp-conventions.html)), yo

    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 sche

    but adhering to convention will save you time.

    Check out CakePHP Conventions (getting-started/cakephp-conventions.html)for m

    information, but suffice it to say that naming our table posts automatically hooks itour Post model, and having fields called modified and created will be automagica

    managed by CakePHP.

    CakePHP Database ConfigurationOnward and upward: lets tell CakePHP where our database is and how to connect

    it. For many, this is the first and last time you configure anything.

    A copy of CakePHPs database configuration file is found in

    /app/Config/database.php.default. Make a copy of this file in the samedirectory, but name it database.php.

    The config file should be pretty straightforward: just replace the values in the

    $defaultarray with those that apply to your setup. A sample completed configura

    array might look something like the following:

    http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.htmlhttp://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    4/18

    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 youve saved your new database.phpfile, 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 t

    the database.

    Optional ConfigurationThere are a few other items that can be configured. Most developers complete the

    laundry-list items, but theyre not required for this tutorial. One is defining a custom

    string (or salt) for use in security hashes. The second is defining a custom numb

    (or seed) for use in encryption.

    The security salt is used for generating hashes. Change the default Security.sa

    value in /app/Config/core.php. The replacement value should be long, hard toguess and be as random as you can make it:

    /*** A random string used in security hashing methods.*/Configure::write('Security.salt', 'pl345e-P45s_7h3*S@l7!');

    The cipher seed is used for encrypt/decrypt strings. Change the default

    Security.cipherSeedvalue by editing /app/Config/core.php. The replacem

    value should be a large random integer:

    /*** A random numeric string (digits only) used to encrypt/decryp*/Configure::write('Security.cipherSeed', '7485712659625147843639

    A Note on mod_rewrite

    Remember that youll need to have PDO, and pdo_mysql enabled in your

    php.ini.

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    5/18

    Occasionally new users will run into mod_rewrite issues. For example if the CakeP

    welcome page looks a little funny (no images or CSS styles), it probably means

    mod_rewrite is not functioning on your system. Please refer to one of the sections

    below about URL rewriting for your webserver to get you up and running:

    URL Rewriting

    Apache and mod_rewrite (and .htaccess)

    Pretty URLs on nginx

    URL Rewrites on IIS7 (Windows hosts)

    I dont / cant use URL rewriting

    Now continue to Blog Tutorial - Adding a layer (tutorials-and-examples/blog/part-

    two.html)to start building your first CakePHP application.

    Blog Tutorial - Adding a layer

    Create a Post ModelThe Model class is the bread and butter of CakePHP applications. By creating a

    CakePHP model that will interact with our database, well have the foundation in pla

    needed to do our view, add, edit, and delete operations later.

    CakePHPs model class files go in /app/Model, and the file well be creating will b

    saved to /app/Model/Post.php. The completed file should look like this:

    classPost extendsAppModel {

    }

    Naming conventions are very important in CakePHP. By naming our model Post,

    CakePHP can automatically infer that this model will be used in the PostsControlle

    and will be tied to a database table called posts.

    For more on models, such as table prefixes, callbacks, and validation, check out th

    Models(models.html)chapter of the Manual.

    Create a Posts ControllerNext, well create a controller for our posts. The controller is where all the business

    logic for post interaction will happen. In a nutshell, its the place where you play wit

    the models and get post-related work done. Well place this new controller in a file

    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 (i.e. post.php or posts.php), CakePHP will not recogn

    any of your settings and will use the defaults instead.

    http://book.cakephp.org/2.0/en/models.htmlhttp://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.htmlhttp://book.cakephp.org/2.0/en/installation/url-rewriting.html#i-don-t-can-t-use-url-rewritinghttp://book.cakephp.org/2.0/en/installation/url-rewriting.html#url-rewrites-on-iis7-windows-hostshttp://book.cakephp.org/2.0/en/installation/url-rewriting.html#pretty-urls-on-nginxhttp://book.cakephp.org/2.0/en/installation/url-rewriting.html#apache-and-mod-rewrite-and-htaccesshttp://book.cakephp.org/2.0/en/installation/url-rewriting.html
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    6/18

    called PostsController.phpinside the /app/Controllerdirectory. Heres wh

    the basic controller should look like:

    classPostsController extendsAppController { public$helpers = array('Html', 'Form');}

    Now, lets add an action to our controller. Actions often represent a single function

    interface in an application. For example, when users request

    www.example.com/posts/index (which is also 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:

    classPostsController extendsAppController { public$helpers = array('Html', 'Form');

    publicfunctionindex() { $this->set('posts', $this->Post->find('all')); }}

    By defining function index()in our PostsController, users can now access the log

    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.

    The single instruction in the action uses set()to pass data from the controller to

    view (which well create next). The line sets the view variable called posts equal to

    return value of the find('all')method of the Post model. Our Post model is

    automatically available at $this->Postbecause weve followed CakePHPs namin

    conventions.

    To learn more about CakePHPs controllers, check out the Controllers

    (controllers.html)chapter.

    Creating Post ViewsNow that we have our data flowing to our model, and our application logic and flow

    defined by our controller, lets create a view for the index action we created above.

    CakePHP views are just presentation-flavored fragments that fit inside an applicati

    layout. For most applications theyre HTML mixed with PHP, but they may end up a

    XML, CSV, or even binary data.

    You may be tempted to name your controllers and actions a certain way to

    obtain a certain URL. Resist that temptation. Follow CakePHP conventions

    (plural controller names, etc.) and create readable, understandable action

    names. You can map URLs to your code using routes covered later on.

    http://book.cakephp.org/2.0/en/controllers.html
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    7/18

    Layouts are presentation code that is wrapped around a view, and can be defined

    switched between, but for now, lets just use the default.

    Remember in the last section how we assigned the posts variable to the view usin

    the set()method? That would hand down data to the view that would look somet

    like this:

    // print_r($posts) output:

    Array( [0] =>Array ( [Post] =>Array ( [id] => 1 [title] => The title [body] => Thisis the post body. [created] => 2008-02-13 18:34:55 [modified] => ) )

    [1] =>Array ( [Post] =>Array ( [id] => 2 [title] => A title once again [body] =>Andthe post body follows. [created] => 2008-02-13 18:34:56 [modified] => ) ) [2] =>Array ( [Post] =>Array ( [id] => 3 [title] => Title strikes back [body] => Thisis really exciting!Not. [created] => 2008-02-13 18:34:57 [modified] => ) ))

    CakePHPs view files are stored in /app/Viewinside a folder named after the

    controller they correspond to (well have to create a folder named Posts in this ca

    To format this post data in a nice table, our view code might look something like thi

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    8/18

    Blog posts Id Title Created

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    9/18

    classPostsController extendsAppController { public$helpers = array('Html', 'Form');

    publicfunctionindex() { $this->set('posts', $this->Post->find('all')); }

    publicfunctionview($id = null) { if(!$id) { thrownewNotFoundException(__('Invalid post')); }

    $post = $this->Post->findById($id); if(!$post) { thrownewNotFoundException(__('Invalid post')); } $this->set('post', $post); }}

    The set()call should look familiar. Notice were using findById()rather than

    find('all')because we only really want a single posts information.

    Notice that our view action takes a parameter: the ID of the post wed like to see. T

    parameter is handed to the action through the requested URL. If a user requests

    /posts/view/3, then the value 3 is passed as $id .

    We also do a bit of error checking to ensure a user is actually accessing a record.

    user requests /posts/view, we will throw a NotFoundExceptionand let the

    CakePHP ErrorHandler take over. We also perform a similar check to make sure th

    user has accessed a record that exists.

    Now lets create the view for our new view action and place it in/app/View/Posts/view.ctp

    Created:

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    10/18

    classPostsController extendsAppController { public$helpers = array('Html', 'Form', 'Session'); public$components = array('Session');

    publicfunctionindex() { $this->set('posts', $this->Post->find('all')); }

    publicfunctionview($id) { if(!$id) { thrownewNotFoundException(__('Invalid post')); }

    $post = $this->Post->findById($id); if(!$post) { thrownewNotFoundException(__('Invalid post')); } $this->set('post', $post); }

    publicfunctionadd() { if($this->request->is('post')) { $this->Post->create();

    if($this->Post->save($this->request->data)) {

    $this->Session->setFlash(__('Your post has been return$this->redirect(array('action' => 'index } $this->Session->setFlash(__('Unable to add your pos } }}

    Heres what the add()action does: if the HTTP method of the request was POST,

    to save the data using the Post model. If for some reason it doesnt save, just rend

    the view. This gives us a chance to show the user validation errors or other warnin

    Every CakePHP request includes a CakeRequestobject which is accessible using

    $this->request. The request object contains useful information regarding the

    request that was just received, and can be used to control the flow of your applicat

    In this case, we use the CakeRequest::is()(controllers/request-

    response.html#CakeRequest::is)method to check that the request is a HTTP POSrequest.

    When a user uses a form to POST data to your application, that information is

    available in $this->request->data. You can use the pr()(core-libraries/globa

    constants-and-functions.html#pr) or debug() (development/debugging.html#debu

    functions to print it out if you want to see what it looks like.

    We use the SessionComponents SessionComponent::setFlash()(core-

    libraries/components/sessions.html#SessionComponent::setFlash) method to set a

    message to a session variable to be displayed on the page after redirection. In the

    You need to include the SessionComponent - and SessionHelper - in any

    controller where you will use it. If necessary, include it in your AppControlle

    http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#SessionComponent::setFlashhttp://book.cakephp.org/2.0/en/development/debugging.html#debughttp://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#prhttp://book.cakephp.org/2.0/en/controllers/request-response.html#CakeRequest::is
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    11/18

    layout we have SessionHelper::flash(core-

    libraries/helpers/session.html#SessionHelper::flash)which displays the message a

    clears the corresponding session variable. The controllers Controller::redire

    (controllers.html#Controller::redirect)function redirects to another URL. The param

    array('action' => 'index')translates to URL /posts i.e the index action of p

    controller. You can refer to Router::url() (development/routing.html#Router::u

    function on theAPI (http://api20.cakephp.org)to see the formats in which you can

    specify a URL for various CakePHP functions.

    Calling the save()method will check for validation errors and abort the save if anoccur. Well discuss how those errors are handled in the following sections.

    Data ValidationCakePHP goes a long way in taking the monotony out of form input validation.

    Everyone hates coding up endless forms and their validation routines. CakePHP

    makes it easier and faster.

    To take advantage of the validation features, youll need to use CakePHPs

    FormHelper in your views. The FormHelper(core-libraries/helpers/form.html#FormHelper)is available by default to all views at $thi

    >Form.

    Heres our add view:

    Add Post

    Here, we use the FormHelper to generate the opening tag for an HTML form. Here

    the HTML that $this->Form->create()generates:

    If create()is called with no parameters supplied, it assumes you are building a fo

    that submits to the current controllers add()action (or edit()action when id is

    included in the form data), via POST.

    The $this->Form->input()method is used to create form elements of the same

    name. The first parameter tells CakePHP which field they correspond to, and the

    second parameter allows you to specify a wide array of options - in this case, the

    number of rows for the textarea. Theres a bit of introspection and automagic here

    input()will output different form elements based on the model field specified.

    http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelperhttp://api20.cakephp.org/http://book.cakephp.org/2.0/en/development/routing.html#Router::urlhttp://book.cakephp.org/2.0/en/controllers.html#Controller::redirecthttp://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#SessionHelper::flash
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    12/18

    The $this->Form->end()call generates a submit button and ends the form. If a

    string is supplied as the first parameter to end(), the FormHelper outputs a subm

    button named accordingly along with the closing form tag. Again, refer to Helpers

    (views/helpers.html)for more on helpers.

    Now lets go back and update our /app/View/Posts/index.ctpview to include

    new Add Post link. Before the , add the following line:

    You may be wondering: how do I tell CakePHP about my validation requirements?

    Validation rules are defined in the model. Lets look back at our Post model and m

    a few adjustments:

    classPost extendsAppModel { public$validate = array(

    'title' => array( 'rule' => 'notEmpty' ), 'body' => array( 'rule' => 'notEmpty' ) );}

    The $validatearray tells CakePHP how to validate your data when the save()

    method is called. Here, Ive specified that both the body and title fields must not be

    empty. CakePHPs validation engine is strong, with a number of pre-built rules (crecard numbers, email addresses, etc.) and flexibility for adding your own validation

    rules. For more information on that setup, check the Data Validation(models/data-

    validation.html).

    Now that you have your validation rules in place, use the app to try to add a post w

    an empty title or body to see how it works. Since weve used the

    FormHelper::input() (core-libraries/helpers/form.html#FormHelper::input)meth

    of the FormHelper to create our form elements, our validation error messages will

    shown automatically.

    Editing PostsPost editing: here we go. Youre a CakePHP pro by now, so you should have picke

    a pattern. Make the action, then the view. Heres what the edit()action of the

    PostsController would look like:

    http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputhttp://book.cakephp.org/2.0/en/models/data-validation.htmlhttp://book.cakephp.org/2.0/en/views/helpers.html
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    13/18

    publicfunctionedit($id = null) { if(!$id) { thrownewNotFoundException(__('Invalid post')); }

    $post = $this->Post->findById($id); if(!$post) { thrownewNotFoundException(__('Invalid post')); }

    if($this->request->is(array('post', 'put'))) { $this->Post->id = $id; if($this->Post->save($this->request->data)) { $this->Session->setFlash(__('Your post has been upd return$this->redirect(array('action' => 'index')); } $this->Session->setFlash(__('Unable to update your post }

    if(!$this->request->data) { $this->request->data = $post; }}

    This action first ensures that the user has tried to access an existing record. If they

    havent passed in an $id parameter, or the post does not exist, we throw a

    NotFoundExceptionfor the CakePHP ErrorHandler to take care of.

    Next the action checks whether the request is either a POST or a PUT request. If it

    then we use the POST data to update our Post record, or kick back and show the

    validation errors.

    If there is no data set to $this->request->data, we simply set it to the previous

    retrieved post.

    The edit view might look something like this:

    Edit Post

    This view outputs the edit form (with the values populated), along with any necess

    validation error messages.

    One thing to note here: CakePHP will assume that you are editing a model if the id

    field is present in the data array. If no id is present (look back at our add view),

    CakePHP will assume that you are inserting a new model when save()is called.

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    14/18

    You can now update your index view with links to edit specific posts:

    Blog posts

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    15/18

    publicfunctiondelete($id) { if($this->request->is('get')) { thrownewMethodNotAllowedException(); }

    if($this->Post->delete($id)) { $this->Session->setFlash( __('The post with id: %s has been deleted.', h($id) ); return$this->redirect(array('action' => 'index')); }}

    This logic deletes the post specified by $id, and uses $this->Session-

    >setFlash()to show the user a confirmation message after redirecting them on t

    /posts. If the user attempts to do a delete using a GET request, we throw an

    Exception. Uncaught exceptions are captured by CakePHPs exception handler, an

    nice error page is displayed. There are many built-in Exceptions

    (development/exceptions.html)that can be used to indicate the various HTTP erro

    your application might need to generate.

    Because were just executing some logic and redirecting, this action has no view. Y

    might want to update your index view with links that allow users to delete posts,

    however:

    http://book.cakephp.org/2.0/en/development/exceptions.html
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    16/18

    Blog posts

  • 8/13/2019 Getting Started CakePHP Cookbook v2

    17/18

    For some, CakePHPs default routing works well enough. Developers who are sens

    to user-friendliness and general search engine compatibility will appreciate the wa

    that CakePHPs URLs map to specific actions. So well just make a quick change to

    routes in this tutorial.

    For more information on advanced routing techniques, see Routes Configuration

    (development/routing.html#routes-configuration) .

    By default, CakePHP responds to a request for the root of your site (i.e.

    http://www.example.com (http://www.example.com)) using its PagesController,rendering a view called home. Instead, well replace this with our PostsController

    creating a routing rule.

    CakePHPs routing is found in /app/Config/routes.php. Youll want to commen

    or remove the line that defines the default root route. It looks like this:

    Router::connect( '/', array('controller' => 'pages', 'action' => 'display', 'home);

    This line connects the URL / with the default CakePHP home page. We want it to

    connect with our own controller, so replace that line with this one:

    Router::connect('/', array('controller' => 'posts', 'action' =>

    This should connect users requesting / to the index() action of our PostsControlle

    ConclusionCreating applications this way will win you peace, honor, love, and money beyond

    your wildest fantasies. Simple, isnt it? Keep in mind that this tutorial was very basic

    CakePHP has manymore features to offer, and is flexible in ways we didnt wish to

    cover here for simplicitys sake. Use the rest of this manual as a guide for building

    more feature-rich applications.

    Now that youve created a basic CakePHP application youre ready for the real thin

    Start your own project, read the rest of the Cookbook(index.html)andAPI

    (http://api20.cakephp.org).

    CakePHP also makes use of reverse routing - if with the above route defin

    you pass array('controller' => 'posts', 'action' => 'index')

    a function expecting an array, the resultant URL used will be /. Its therefo

    a good idea to always use arrays for URLs as this means your routes defin

    where a URL goes, and also ensures that links point to the same place too

    http://api20.cakephp.org/http://book.cakephp.org/2.0/en/index.htmlhttp://www.example.com/http://book.cakephp.org/2.0/en/development/routing.html#routes-configuration
  • 8/13/2019 Getting Started CakePHP Cookbook v2

    18/18