SlideShare uma empresa Scribd logo
1 de 40
Baixar para ler offline
CakePHP   Bakery   API   Manual   Forge   Trac




                                  1.2 @ OCPHP
                                                 August 9, 2007




                                                                  © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                              Why CakePHP?
                    MVC architecture
                    Convention over Configuration
                    Flexible and Extensible
                    Write less, do more
                    Open Source, Large Community
                    MIT License

                                                   © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




           CakePHP the right way


                                                             by: Amy Hoy, http://slash7.com/




                                          Think twice, code once
                                               Loose couple


                                                                                           © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                   Hot out of the oven
                          Behaviors              Router

                          “With” Associations    Email

                          Enhanced Validation    Security

                          Forms                  Authentication

                          Pagination             Configure

                          i18n + l10n            Cache Engines

                          Acl                    Console




                                                                  © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                             Behaviors
                    extend models
                    encapsulate reusable functionality
                    use callbacks for automagic




                                                         © 2007 Cake Software Foundation
CakePHP   Bakery   API     Manual   Forge   Trac




                   <?php
                   class CoolBehavior extends ModelBehavior {

                         var $settings = array();

                         function setup(&$model, $config = array()) {
                             $this->settings = $config;
                         }
                         /* Callbacks */
                         function beforeFind(&$model, $query) { }

                         function afterFind(&$model, $results, $primary) { }

                         function beforeSave(&$model) { }

                         function afterSave(&$model, $created) { }

                         function beforeDelete(&$model) { }

                         function afterDelete(&$model) { }

                         function onError(&$model, $error) { }

                         /* Custom Methods */
                         function myCustomMethod(&$model, $data = array()) {
                             return array_merge($model->data, $data);
                         }
                   }
                   ?>
                                                                               © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac



           <?php
           class Post extends AppModel {

                var $actsAs = array(‘Cool’=>array(‘field’=>’cool_id’));

                function doSomething($cool = null) {
                   $this->myCustomMethod(array(‘cool_id’=> $cool));
                }

           }
           ?>

           <?php
           class PostsController extends AppController {
              var $name = ‘Posts’;

                function index() {
                   $this->set(‘posts’, $this->Post->doSomething(5));
                }

           }
           ?>


                                                                         © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                   “With” Associations
                    enables extra fields in join tables
                    access to model for join table

                                                               tags
                   posts                         posts_tag   id
           id                                        s       key
           title                                 id
                                                             name
           body                                  post_id     created
           created                               tag_id      modified
           modified                               date
                                                                      © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                  Adding “With”
                         <?php
                         class Post extends AppModel {

                              var $hasAndBelongsToMany = array(
                         
      
   
   
   
    
  
   
    ‘Tag’ => array(
                         
      
   
   
   
    
  
   
    
     ‘className’ => ’Tag’,
                         
      
   
   
   
    
  
   
    
     ‘with’ => ‘TaggedPost’,
                         	      	   	   	   	    	  	   	    )
                         	      	   	   	   	    	  	   );

                              function beforeSave() {
                                 if(!empty($this->data[‘Tag’])) {
                                       $this->TaggedPost->save($this->data[‘Tag’]);
                                 }
                              }

                         }
                         ?>

                                                                                             © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                    Using “With”
                    <?php
                    class PostsController extends AppController {
                       var $name = ‘Posts’;

                         function tags() {
                            $this->set(‘tags’, $this->Post->TaggedPost->findAll());
                         }
                    }
                    ?>
                    <?php
                      foreach ($tags as $tag) :
                         echo $tag[‘Post’][‘title’];

                           echo $tag[‘Tag’][‘name’];

                           echo $tag[‘TaggedPost’][‘date’];

                         endforeach;
                    ?>
                                                                                     © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                           Validation is King
                   alphaNumeric                  email       number


                   between                       equalTo     numeric


                   blank                         file         phone


                   cc                            ip          postal


                   comparison                    maxLength   ssn


                   custom                        minLength   url


                   date                          money       userDefined


                   decimal                       multiple




                                                                          © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                              Using Validation
             <?php
             class Post extends AppModel {

                   var $validate = array(
                         'title' => array(
                             'required' => VALID_NOT_EMPTY,
                             'length' => array( 'rule' => array('maxLength', 100))
                         ),
                         'body' => VALID_NOT_EMPTY
                      );

             }
             ?>




                                                                                     © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                     Forms made simple
             <?php 

             
      echo $form->create('Post');
                
             
      echo $form->input('title', array('error' => array(
                     
 
     
   
    
      
     
    
     'required' => 'Please specify a valid title',
                     
 
     
   
    
      
     
    
     'length' => 'The title must have no more than 100 characters'
                 
 
    
    
   
    
      
     
    
     )
             	      	   	    	   	    	      	     	    )
             
      
   
    
   
    ); 

             
     echo $form->input('body', array('error' => 'Please specify a valid body'));
             	
             
     echo $form->end('Add');
             ?>




                                                                                                                    © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                         More about Forms
             <?php 
                 /* Change the action */
             
   echo $form->create('User', array(‘action’=> ‘login’));
             ?>

             <?php 
                 /* Change the type for uploading files */
                 echo $form->create('Image', array(‘type’=> ‘file’));
                      echo $form->input('file', array(‘type’=> ‘file’));
                 echo $form->end(‘Upload’);
             ?>


             <?php 
                 /* the three line form */
                 echo $form->create('Post');
                      echo $form->inputs(‘Add a Post’);
                 echo $form->end(‘Add’);
             ?>




                                                                          © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




             <?php
                                            Pagination
             class PostsController extends AppController {
                var $name = ‘Posts’;

                   var $paginate = array(‘order’=> ‘Post.created DESC’);

                   function index() {
                      $this->set(‘posts’, $this->paginate());
                   }
             }
             ?>
            <?php
            echo $paginator->counter(array(
                'format' => 'Page %page% of %pages%, showing %current% records out of
                %count% total, starting on record %start%, ending on %end%'
            ));
            echo $paginator->prev('<< previous', array(), null, array('class'=>'disabled'));
            echo $paginator->numbers();
            echo $paginator->sort(‘Created’);
            echo $paginator->next('next >>', array(), null, array('class'=>'disabled'));
                                                                                           © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                            i18n/L10n
                    built in gettext for static strings
                    TranslationBehavior for dynamic
                    data
                    console extractor




                                                          © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                      gettext style
          <?php
          /* echo a string */
          __(‘Translate me’);

          /* return a string */
          $html->link(__(‘Translate me’, true), array(‘controller’=>’users’));

          /* by category : LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.*/
          __c(‘Translate me’, ‘LC_CTYPE’);

          /* get plurals by number*/
          __n(‘Translate’, ‘Translates’, 2);

          /* override the domain.*/
          __d(‘posts’, ‘Translate me’);

          /* override the domain by category.*/
          __dc(‘posts’, ‘Translate me’, ‘LC_CTYPE’);


                                                                                                           © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                   Translation Behavior
             <?php
             class Post extends AppModel {

                   var $actsAs = array(‘Translation’=> array(‘title’, ‘body’));

             }
             ?>
             CREATE TABLE i18n (                             CREATE TABLE i18n_content (
             	   id int(10) NOT NULL auto_increment,         	   id int(10) NOT NULL auto_increment,
             	   locale varchar(6) NOT NULL,                 	   content text,
             	   i18n_content_id int(10) NOT NULL,           	   PRIMARY KEY (id)
             	   model varchar(255) NOT NULL,                );
             	   row_id int(10) NOT NULL,
             	   field varchar(255) NOT NULL,
             	   PRIMARY KEY	 (id),
             	   KEY locale	 (locale),
             	   KEY i18n_content_id (i18n_content_id),
             	   KEY row_id	(row_id),
             	   KEY model	 (model),
             	   KEY field (field)
             );



                                                                                                  © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                                 Acl
                    abstracted for maximum
                    compatibility
                    component for controller
                    behavior for model




                                                       © 2007 Cake Software Foundation
CakePHP       Bakery   API   Manual   Forge   Trac




                                          Acl behavior
    <?php                                                          <?php
    class User extends AppModel {                                  class Post extends AppModel {

          var $actsAs = array(‘Acl’=> ‘requester’);                     var $actsAs = array(‘Acl’=> ‘controlled’);

          function parentNode() {}                                      function parentNode() {}

          function bindNode($object) {                                  function bindNode($object) {}
                if (!empty($object['User']['role'])) {
          	           return 'Roles/' . $object['User']['role'];   }
                }                                                  ?>
          }

          function roles() {
             return $this->Aro->findAll();
          }
    }
    ?>


                                                                                                   © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                                 Routing
                    reverse routes
                    magic variables
                    named parameters
                    parseExtensions
                    REST resource mapping



                                                           © 2007 Cake Software Foundation
CakePHP    Bakery   API   Manual   Forge   Trac




                           Reversing Routes
          <?php
          Route::connect(‘/’, array(‘controller’=>’pages’, ‘action’=>’display’, ‘home’));
          ?>


      <?php
      echo $html->link(‘Go Home’, array(‘controller’=> ‘pages’, ‘action’=> ‘display’, home));
      ?>




                                                                                            © 2007 Cake Software Foundation
CakePHP   Bakery   API    Manual   Forge   Trac




                                   Magic Variables
               	         $Action	 => Matches most common action names

               	         $Year	     => Matches any year from 1000 to 2999

               	         $Month	 => Matches any valid month with a leading zero (01 - 12)

               	         $Day	      => Matches any valid day with a leading zero (01 - 31)

               	         $ID		      => Matches any valid whole number (0 - 99999.....)
                         Router::connect(
                         	   '/:controller/:year/:month/:day',
                         	   array('action' => 'index', 'day' => null),
                         	   array('year' => $Year, 'month' => $Month, 'day' => $Day)
                         );

                         Router::connect(
                         	   '/:controller/:id',
                         
   array('action' => 'index', ‘id’=> ‘1’), array('id' => $ID)
                         );
                                                                                             © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge    Trac




                                      Named Args
                                    http://cakephp.org/posts/index/page:2/sort:title

                                   <?php
                                   class PostsController extends AppController {
                                      var $name = ‘Posts’;

                                          function index() {
                                             $this->passedArgs[‘page’];
                                             $this->passedArgs[‘sort’];
                                          }

                                   }
                                   ?>




                                                                                       © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                         Parsing Extensions
                         /* get everything */
                         Router::parseExtensions();
                         /* more fine grained */
                         Router::parseExtensions(‘xml’, ‘html’);

                         maps views to unique locations
                         http://cakephp.org/posts/index.rss
                          Router::parseExtensions(‘rss’);
                         <?php //app/views/posts/rss/index.ctp
                         	    echo $rss->items($posts, 'transformRSS');
                         	    function transformRSS($post) {
                         	    	      return array(
                         	    	      	     'title'	 	    	     => $post['Post']['title'],
                         	    	      	     'link'	 	     	     => array('url'=>'/posts/view/'.$post['Post]['id']),
                         	    	      	     'description'	      => substr($post['Post']['body'], 0, 200),
                         	    	      	     'pubDate'	 	        => date('r', strtotime($post['Post']['created'])),
                         	    	      );
                         	    }
                         ?>


                                                                                                                     © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                                      Email
                   $this->Email->to = $user['User']['email'];
                   $this->Email->from = Configure::read('Site.email');
                   $this->Email->subject = Configure::read('Site.name').' Password Reset URL';

                   $content[] = 'A request to reset you password has been submitted to '.Configure::read('Site.name');
                   $content[] = 'Please visit the following url to have your temporary password sent';
                   $content[] = Router::url('/users/verify/reset/'.$token, true);

                   if($this->Email->send($content)) {
                   	      $this->Session->setFlash('You should receive an email with further instruction shortly');
                   	      $this->redirect('/', null, true);
                   }


                   /* Sending HTML and Text */
                   $this->Email->sendAs = ‘both’;
                   $this->Email->template = ‘reset_password’;

                   /* HTML templates */
                   //app/views/elements/email/html/reset_password.ctp

                   /* TEXT templates */
                   //app/views/elements/email/text




                                                                                                                      © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                                 Security
                                                 HTTP Auth
                                  <?php
                                  class PostsController extends AppController {
                                     var $name = ‘Posts’;

                                       var $components = array(‘Security’);

                                       function beforeFilter() {
                                          $this->Security->requireLogin(‘add’, ‘edit’, ‘delete’);
                                          $this->Security->loginUsers = array('cake'=>'tooeasy');
                                       }

                                  }
                                  ?>




                                                                                                    © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                  Authentication
                             <?php
                             class PostsController extends AppController {
                                var $name = ‘Posts’;

                                  var $components = array(‘Auth’);

                             }
                             ?>


                              authenticate any model: User, Member, Editor, Contact

                              authorize against models, controllers, or abstract
                              objects

                              automate login




                                                                                   © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual     Forge   Trac




                                            Auth setup
                         <?php
                         class PostsController extends AppController {
                         
      var $name = ‘Posts’;

                         
        var $components = array(‘Auth’);

                         	      function beforeFilter() {
                         	      	      $this->Auth->userModel = 'Member';
                              	       $this->Auth->loginAction = '/members/login';
                         	      	      $this->Auth->loginRedirect = '/members/index';
                         	      	      $this->Auth->fields = array('username' => 'username', 'password' => 'pword');
                         	      	
                         	      	      $this->Auth->authorize = array('model'=>'Member');
                         	      	      $this->Auth->mapActions(array(
                         	      	      	     'read' => array('display'),
                         	      	      	     'update' => array('admin_show', 'admin_hide'),
                         	      	      ));
                         	      	
                         	      }
                         }
                         ?>




                                                                                                                  © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                         Authorize a Model
                     <?php
                     class Member extends Model {
                     	    var $name = 'Member';
                     	
                     	    function isAuthorized($user, $controller, $action) {
                     	
                     	    	    switch ($action) {
                     	    	    	    case 'default':
                     	    	    	    	    return false;
                     	    	    	    break;
                     	    	    	    case 'delete':
                     	    	    	    	    if($user[['Member']['role'] == 'admin') {
                     	    	    	    	    	    return true;
                     	    	    	    	    }
                     	    	    	    break;	 	
                     	    	    }
                     	    }
                     }
                     ?>

                                                                                     © 2007 Cake Software Foundation
CakePHP   Bakery   API    Manual   Forge   Trac




           Authorize a Controller
                     <?php
                     class PostsController extends AppController {
                     
    var $name = ‘Posts’;

                     
      var $components = array(‘Auth’);

                     	      function beforeFilter() {
                     
      
    $this->Auth->authorize = ‘controller’;
                     	      }
                     	
                     	      function isAuthorized() {
                     	      	    if($this->Auth->user('role') == 'admin') {
                     	      	    	    return true;
                     	      	    }
                     	      }
                     }
                     ?>



                                                                              © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                          Authorize CRUD
                           <?php
                           class PostsController extends AppController {
                           
    var $name = ‘Posts’;

                           
      var $components = array(‘Auth’);

                           	      function beforeFilter() {
                           
      
    $this->Auth->authorize = ‘crud’;
                                       $this->Auth->actionPath = 'Root/';
                           	      }
                           }
                           ?>
                           $this->Acl->allow('Roles/Admin', 'Root');
                           $this->Acl->allow('Roles/Admin', 'Root/Posts');




                                                                             © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                            Configure
                   <?php

                   Configure::write(‘Oc.location’, ‘Buddy Group’);

                   Configure::write(‘Oc’, array(‘location’=>‘Buddy Group’));

                   Configure::read(‘Oc.location’);

                   Configure::store('Groups', 'groups',
                                     array('Oc' => array(‘location’=>’Buddy Group’)));

                   Configure::load('groups');

                   ?>




                                                                                         © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge    Trac




                                  Cache Engines
                                    File                          xcache

                                    APC                           Model

                                    Memcache


                             Cache::engine(‘File’, [settings]);

                             $data = Cache::read(‘post’);
                             if(empty($data)) {
                                 $data = $this->Post->findAll();
                                 Cache::write(‘post’, $data);
                             }




                                                                           © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                                 Console
                           Makes writing Command Line
                           Interfaces (CLI) cake
                           Shells
                           Tasks
                           Access to models




                                                           © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                          Core Shells
                                                 Acl
                                                 Extractor
                                                 Bake
                                                 Console
                                                 API



                                                             © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                  The Bake Shell
                                          Tasks

                                                 Model -   cake bake model Post

                                                 Controller - cake bake controller Posts

                                                 View -   cake bake view Posts

                                                 DbConfig -      cake bake db_config

                                                 Project - cake bake project



                            Custom view templates, oh yeah!



                                                                                           © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                              Your Own Shell
                                      <?php
                                      class DemoShell extends Shell {
                                      	
                                      	      var $uses = array('Post');
                                      	
                                      	      var $tasks = array('Whatever', 'Another');
                                      	
                                      	      function initialize() {}
                                      	
                                      	      function startup() {}
                                      	      	
                                      	      function main() {
                                      	      	      $this->out('Demo Script');
                                      	      }
                                      	
                                      	      function something() {
                                      	      	      $this->Whatver->execute();
                                      	      }
                                      	
                                      	      function somethingElse() {
                                          	         $posts = $this->Post->findAll();
                                                    foreach($posts as $post) {
                                                      $this->out(‘title : ‘ . $post[‘Post’][‘title’]);
                                          	         }
                                             }
                                      }
                                      ?>

                                                                                                         © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                                 More....
                                  Xml reading and writing
                                  HttpSockets
                                  Themes
                                  Cookies
                                  ......



                                                            © 2007 Cake Software Foundation
CakePHP   Bakery   API   Manual   Forge   Trac




                                    Questions?




                                                 © 2007 Cake Software Foundation

Mais conteúdo relacionado

Mais procurados

Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with MagentoMagento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magentovarien
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastMichelangelo van Dam
 
Curso Symfony - Clase 2
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2Javier Eguiluz
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4Javier Eguiluz
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09Michelangelo van Dam
 
Integrating powl with web dynpro abap.
Integrating powl with web dynpro abap.Integrating powl with web dynpro abap.
Integrating powl with web dynpro abap.Adesh Chauhan
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your AppLuca Mearelli
 
Programming in java_-_17_-_swing
Programming in java_-_17_-_swingProgramming in java_-_17_-_swing
Programming in java_-_17_-_swingjosodo
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Michelangelo van Dam
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Testing API platform with Behat BDD tests
Testing API platform with Behat BDD testsTesting API platform with Behat BDD tests
Testing API platform with Behat BDD testsStefan Adolf
 

Mais procurados (15)

Symfony Components
Symfony ComponentsSymfony Components
Symfony Components
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Apc Memcached Confoo 2011
Apc Memcached Confoo 2011Apc Memcached Confoo 2011
Apc Memcached Confoo 2011
 
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with MagentoMagento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Curso Symfony - Clase 2
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Integrating powl with web dynpro abap.
Integrating powl with web dynpro abap.Integrating powl with web dynpro abap.
Integrating powl with web dynpro abap.
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
 
Programming in java_-_17_-_swing
Programming in java_-_17_-_swingProgramming in java_-_17_-_swing
Programming in java_-_17_-_swing
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Testing API platform with Behat BDD tests
Testing API platform with Behat BDD testsTesting API platform with Behat BDD tests
Testing API platform with Behat BDD tests
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 

Semelhante a CakePHP Fundamentals - 1.2 @ OCPHP

Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2markstory
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for MagentoIvan Chepurnyi
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web FrameworkLuther Baker
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Michael Wales
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesScala Italy
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsNeil Crookes
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 
HC - The Mobile Adventure with Phonegap
HC - The Mobile Adventure with PhonegapHC - The Mobile Adventure with Phonegap
HC - The Mobile Adventure with Phonegaphockeycommunity
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Google Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and BeyondGoogle Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and Beyonddion
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
Getting Ignited with EE2
Getting Ignited with EE2Getting Ignited with EE2
Getting Ignited with EE2jamierumbelow
 
Deep dive into feature versioning in SharePoint 2010
Deep dive into feature versioning in SharePoint 2010Deep dive into feature versioning in SharePoint 2010
Deep dive into feature versioning in SharePoint 2010Jeremy Thake
 

Semelhante a CakePHP Fundamentals - 1.2 @ OCPHP (20)

Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for Magento
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Enterprise Cake
Enterprise CakeEnterprise Cake
Enterprise Cake
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservices
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
HC - The Mobile Adventure with Phonegap
HC - The Mobile Adventure with PhonegapHC - The Mobile Adventure with Phonegap
HC - The Mobile Adventure with Phonegap
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Bake by cake php2.0
Bake by cake php2.0Bake by cake php2.0
Bake by cake php2.0
 
Google Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and BeyondGoogle Back To Front: From Gears to App Engine and Beyond
Google Back To Front: From Gears to App Engine and Beyond
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Api Design
Api DesignApi Design
Api Design
 
Getting Ignited with EE2
Getting Ignited with EE2Getting Ignited with EE2
Getting Ignited with EE2
 
Deep dive into feature versioning in SharePoint 2010
Deep dive into feature versioning in SharePoint 2010Deep dive into feature versioning in SharePoint 2010
Deep dive into feature versioning in SharePoint 2010
 

Último

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

CakePHP Fundamentals - 1.2 @ OCPHP

  • 1. CakePHP Bakery API Manual Forge Trac 1.2 @ OCPHP August 9, 2007 © 2007 Cake Software Foundation
  • 2. CakePHP Bakery API Manual Forge Trac Why CakePHP? MVC architecture Convention over Configuration Flexible and Extensible Write less, do more Open Source, Large Community MIT License © 2007 Cake Software Foundation
  • 3. CakePHP Bakery API Manual Forge Trac CakePHP the right way by: Amy Hoy, http://slash7.com/ Think twice, code once Loose couple © 2007 Cake Software Foundation
  • 4. CakePHP Bakery API Manual Forge Trac Hot out of the oven Behaviors Router “With” Associations Email Enhanced Validation Security Forms Authentication Pagination Configure i18n + l10n Cache Engines Acl Console © 2007 Cake Software Foundation
  • 5. CakePHP Bakery API Manual Forge Trac Behaviors extend models encapsulate reusable functionality use callbacks for automagic © 2007 Cake Software Foundation
  • 6. CakePHP Bakery API Manual Forge Trac <?php class CoolBehavior extends ModelBehavior { var $settings = array(); function setup(&$model, $config = array()) { $this->settings = $config; } /* Callbacks */ function beforeFind(&$model, $query) { } function afterFind(&$model, $results, $primary) { } function beforeSave(&$model) { } function afterSave(&$model, $created) { } function beforeDelete(&$model) { } function afterDelete(&$model) { } function onError(&$model, $error) { } /* Custom Methods */ function myCustomMethod(&$model, $data = array()) { return array_merge($model->data, $data); } } ?> © 2007 Cake Software Foundation
  • 7. CakePHP Bakery API Manual Forge Trac <?php class Post extends AppModel { var $actsAs = array(‘Cool’=>array(‘field’=>’cool_id’)); function doSomething($cool = null) { $this->myCustomMethod(array(‘cool_id’=> $cool)); } } ?> <?php class PostsController extends AppController { var $name = ‘Posts’; function index() { $this->set(‘posts’, $this->Post->doSomething(5)); } } ?> © 2007 Cake Software Foundation
  • 8. CakePHP Bakery API Manual Forge Trac “With” Associations enables extra fields in join tables access to model for join table tags posts posts_tag id id s key title id name body post_id created created tag_id modified modified date © 2007 Cake Software Foundation
  • 9. CakePHP Bakery API Manual Forge Trac Adding “With” <?php class Post extends AppModel { var $hasAndBelongsToMany = array( ‘Tag’ => array( ‘className’ => ’Tag’, ‘with’ => ‘TaggedPost’, ) ); function beforeSave() { if(!empty($this->data[‘Tag’])) { $this->TaggedPost->save($this->data[‘Tag’]); } } } ?> © 2007 Cake Software Foundation
  • 10. CakePHP Bakery API Manual Forge Trac Using “With” <?php class PostsController extends AppController { var $name = ‘Posts’; function tags() { $this->set(‘tags’, $this->Post->TaggedPost->findAll()); } } ?> <?php foreach ($tags as $tag) : echo $tag[‘Post’][‘title’]; echo $tag[‘Tag’][‘name’]; echo $tag[‘TaggedPost’][‘date’]; endforeach; ?> © 2007 Cake Software Foundation
  • 11. CakePHP Bakery API Manual Forge Trac Validation is King alphaNumeric email number between equalTo numeric blank file phone cc ip postal comparison maxLength ssn custom minLength url date money userDefined decimal multiple © 2007 Cake Software Foundation
  • 12. CakePHP Bakery API Manual Forge Trac Using Validation <?php class Post extends AppModel { var $validate = array( 'title' => array( 'required' => VALID_NOT_EMPTY, 'length' => array( 'rule' => array('maxLength', 100)) ), 'body' => VALID_NOT_EMPTY ); } ?> © 2007 Cake Software Foundation
  • 13. CakePHP Bakery API Manual Forge Trac Forms made simple <?php  echo $form->create('Post');     echo $form->input('title', array('error' => array(          'required' => 'Please specify a valid title',          'length' => 'The title must have no more than 100 characters'      ) ) );  echo $form->input('body', array('error' => 'Please specify a valid body')); echo $form->end('Add'); ?> © 2007 Cake Software Foundation
  • 14. CakePHP Bakery API Manual Forge Trac More about Forms <?php  /* Change the action */ echo $form->create('User', array(‘action’=> ‘login’)); ?> <?php  /* Change the type for uploading files */ echo $form->create('Image', array(‘type’=> ‘file’)); echo $form->input('file', array(‘type’=> ‘file’)); echo $form->end(‘Upload’); ?> <?php  /* the three line form */ echo $form->create('Post'); echo $form->inputs(‘Add a Post’); echo $form->end(‘Add’); ?> © 2007 Cake Software Foundation
  • 15. CakePHP Bakery API Manual Forge Trac <?php Pagination class PostsController extends AppController { var $name = ‘Posts’; var $paginate = array(‘order’=> ‘Post.created DESC’); function index() { $this->set(‘posts’, $this->paginate()); } } ?> <?php echo $paginator->counter(array( 'format' => 'Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%' )); echo $paginator->prev('<< previous', array(), null, array('class'=>'disabled')); echo $paginator->numbers(); echo $paginator->sort(‘Created’); echo $paginator->next('next >>', array(), null, array('class'=>'disabled')); © 2007 Cake Software Foundation
  • 16. CakePHP Bakery API Manual Forge Trac i18n/L10n built in gettext for static strings TranslationBehavior for dynamic data console extractor © 2007 Cake Software Foundation
  • 17. CakePHP Bakery API Manual Forge Trac gettext style <?php /* echo a string */ __(‘Translate me’); /* return a string */ $html->link(__(‘Translate me’, true), array(‘controller’=>’users’)); /* by category : LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.*/ __c(‘Translate me’, ‘LC_CTYPE’); /* get plurals by number*/ __n(‘Translate’, ‘Translates’, 2); /* override the domain.*/ __d(‘posts’, ‘Translate me’); /* override the domain by category.*/ __dc(‘posts’, ‘Translate me’, ‘LC_CTYPE’); © 2007 Cake Software Foundation
  • 18. CakePHP Bakery API Manual Forge Trac Translation Behavior <?php class Post extends AppModel { var $actsAs = array(‘Translation’=> array(‘title’, ‘body’)); } ?> CREATE TABLE i18n ( CREATE TABLE i18n_content ( id int(10) NOT NULL auto_increment, id int(10) NOT NULL auto_increment, locale varchar(6) NOT NULL, content text, i18n_content_id int(10) NOT NULL, PRIMARY KEY (id) model varchar(255) NOT NULL, ); row_id int(10) NOT NULL, field varchar(255) NOT NULL, PRIMARY KEY (id), KEY locale (locale), KEY i18n_content_id (i18n_content_id), KEY row_id (row_id), KEY model (model), KEY field (field) ); © 2007 Cake Software Foundation
  • 19. CakePHP Bakery API Manual Forge Trac Acl abstracted for maximum compatibility component for controller behavior for model © 2007 Cake Software Foundation
  • 20. CakePHP Bakery API Manual Forge Trac Acl behavior <?php <?php class User extends AppModel { class Post extends AppModel { var $actsAs = array(‘Acl’=> ‘requester’); var $actsAs = array(‘Acl’=> ‘controlled’); function parentNode() {} function parentNode() {} function bindNode($object) { function bindNode($object) {} if (!empty($object['User']['role'])) { return 'Roles/' . $object['User']['role']; } } ?> } function roles() { return $this->Aro->findAll(); } } ?> © 2007 Cake Software Foundation
  • 21. CakePHP Bakery API Manual Forge Trac Routing reverse routes magic variables named parameters parseExtensions REST resource mapping © 2007 Cake Software Foundation
  • 22. CakePHP Bakery API Manual Forge Trac Reversing Routes <?php Route::connect(‘/’, array(‘controller’=>’pages’, ‘action’=>’display’, ‘home’)); ?> <?php echo $html->link(‘Go Home’, array(‘controller’=> ‘pages’, ‘action’=> ‘display’, home)); ?> © 2007 Cake Software Foundation
  • 23. CakePHP Bakery API Manual Forge Trac Magic Variables $Action => Matches most common action names $Year => Matches any year from 1000 to 2999 $Month => Matches any valid month with a leading zero (01 - 12) $Day => Matches any valid day with a leading zero (01 - 31) $ID => Matches any valid whole number (0 - 99999.....) Router::connect( '/:controller/:year/:month/:day', array('action' => 'index', 'day' => null), array('year' => $Year, 'month' => $Month, 'day' => $Day) ); Router::connect( '/:controller/:id', array('action' => 'index', ‘id’=> ‘1’), array('id' => $ID) ); © 2007 Cake Software Foundation
  • 24. CakePHP Bakery API Manual Forge Trac Named Args http://cakephp.org/posts/index/page:2/sort:title <?php class PostsController extends AppController { var $name = ‘Posts’; function index() { $this->passedArgs[‘page’]; $this->passedArgs[‘sort’]; } } ?> © 2007 Cake Software Foundation
  • 25. CakePHP Bakery API Manual Forge Trac Parsing Extensions /* get everything */ Router::parseExtensions(); /* more fine grained */ Router::parseExtensions(‘xml’, ‘html’); maps views to unique locations http://cakephp.org/posts/index.rss Router::parseExtensions(‘rss’); <?php //app/views/posts/rss/index.ctp echo $rss->items($posts, 'transformRSS'); function transformRSS($post) { return array( 'title' => $post['Post']['title'], 'link' => array('url'=>'/posts/view/'.$post['Post]['id']), 'description' => substr($post['Post']['body'], 0, 200), 'pubDate' => date('r', strtotime($post['Post']['created'])), ); } ?> © 2007 Cake Software Foundation
  • 26. CakePHP Bakery API Manual Forge Trac Email $this->Email->to = $user['User']['email']; $this->Email->from = Configure::read('Site.email'); $this->Email->subject = Configure::read('Site.name').' Password Reset URL'; $content[] = 'A request to reset you password has been submitted to '.Configure::read('Site.name'); $content[] = 'Please visit the following url to have your temporary password sent'; $content[] = Router::url('/users/verify/reset/'.$token, true); if($this->Email->send($content)) { $this->Session->setFlash('You should receive an email with further instruction shortly'); $this->redirect('/', null, true); } /* Sending HTML and Text */ $this->Email->sendAs = ‘both’; $this->Email->template = ‘reset_password’; /* HTML templates */ //app/views/elements/email/html/reset_password.ctp /* TEXT templates */ //app/views/elements/email/text © 2007 Cake Software Foundation
  • 27. CakePHP Bakery API Manual Forge Trac Security HTTP Auth <?php class PostsController extends AppController { var $name = ‘Posts’; var $components = array(‘Security’); function beforeFilter() { $this->Security->requireLogin(‘add’, ‘edit’, ‘delete’); $this->Security->loginUsers = array('cake'=>'tooeasy'); } } ?> © 2007 Cake Software Foundation
  • 28. CakePHP Bakery API Manual Forge Trac Authentication <?php class PostsController extends AppController { var $name = ‘Posts’; var $components = array(‘Auth’); } ?> authenticate any model: User, Member, Editor, Contact authorize against models, controllers, or abstract objects automate login © 2007 Cake Software Foundation
  • 29. CakePHP Bakery API Manual Forge Trac Auth setup <?php class PostsController extends AppController { var $name = ‘Posts’; var $components = array(‘Auth’); function beforeFilter() { $this->Auth->userModel = 'Member'; $this->Auth->loginAction = '/members/login'; $this->Auth->loginRedirect = '/members/index'; $this->Auth->fields = array('username' => 'username', 'password' => 'pword'); $this->Auth->authorize = array('model'=>'Member'); $this->Auth->mapActions(array( 'read' => array('display'), 'update' => array('admin_show', 'admin_hide'), )); } } ?> © 2007 Cake Software Foundation
  • 30. CakePHP Bakery API Manual Forge Trac Authorize a Model <?php class Member extends Model { var $name = 'Member'; function isAuthorized($user, $controller, $action) { switch ($action) { case 'default': return false; break; case 'delete': if($user[['Member']['role'] == 'admin') { return true; } break; } } } ?> © 2007 Cake Software Foundation
  • 31. CakePHP Bakery API Manual Forge Trac Authorize a Controller <?php class PostsController extends AppController { var $name = ‘Posts’; var $components = array(‘Auth’); function beforeFilter() { $this->Auth->authorize = ‘controller’; } function isAuthorized() { if($this->Auth->user('role') == 'admin') { return true; } } } ?> © 2007 Cake Software Foundation
  • 32. CakePHP Bakery API Manual Forge Trac Authorize CRUD <?php class PostsController extends AppController { var $name = ‘Posts’; var $components = array(‘Auth’); function beforeFilter() { $this->Auth->authorize = ‘crud’; $this->Auth->actionPath = 'Root/'; } } ?> $this->Acl->allow('Roles/Admin', 'Root'); $this->Acl->allow('Roles/Admin', 'Root/Posts'); © 2007 Cake Software Foundation
  • 33. CakePHP Bakery API Manual Forge Trac Configure <?php Configure::write(‘Oc.location’, ‘Buddy Group’); Configure::write(‘Oc’, array(‘location’=>‘Buddy Group’)); Configure::read(‘Oc.location’); Configure::store('Groups', 'groups', array('Oc' => array(‘location’=>’Buddy Group’))); Configure::load('groups'); ?> © 2007 Cake Software Foundation
  • 34. CakePHP Bakery API Manual Forge Trac Cache Engines File xcache APC Model Memcache Cache::engine(‘File’, [settings]); $data = Cache::read(‘post’); if(empty($data)) { $data = $this->Post->findAll(); Cache::write(‘post’, $data); } © 2007 Cake Software Foundation
  • 35. CakePHP Bakery API Manual Forge Trac Console Makes writing Command Line Interfaces (CLI) cake Shells Tasks Access to models © 2007 Cake Software Foundation
  • 36. CakePHP Bakery API Manual Forge Trac Core Shells Acl Extractor Bake Console API © 2007 Cake Software Foundation
  • 37. CakePHP Bakery API Manual Forge Trac The Bake Shell Tasks Model - cake bake model Post Controller - cake bake controller Posts View - cake bake view Posts DbConfig - cake bake db_config Project - cake bake project Custom view templates, oh yeah! © 2007 Cake Software Foundation
  • 38. CakePHP Bakery API Manual Forge Trac Your Own Shell <?php class DemoShell extends Shell { var $uses = array('Post'); var $tasks = array('Whatever', 'Another'); function initialize() {} function startup() {} function main() { $this->out('Demo Script'); } function something() { $this->Whatver->execute(); } function somethingElse() { $posts = $this->Post->findAll(); foreach($posts as $post) { $this->out(‘title : ‘ . $post[‘Post’][‘title’]); } } } ?> © 2007 Cake Software Foundation
  • 39. CakePHP Bakery API Manual Forge Trac More.... Xml reading and writing HttpSockets Themes Cookies ...... © 2007 Cake Software Foundation
  • 40. CakePHP Bakery API Manual Forge Trac Questions? © 2007 Cake Software Foundation