You are on page 1of 29

Programming in PHP

using…

CakePhp@PhpRoR Solutions 1
Inde
 x
Introduction
 Components needed
 Model-View-Controller
 Directory structure
 Controller
– Components
 Model
– Behaviors
 View
– helpers
 Scaffolding
 Cake console

CakePhp@PhpRoR Solutions 2
Introductio
n
 CakePHP is a free, open-source, rapid development
framework for PHP. It’s a foundational structure for
programmers to create web applications.

 It’s a rapid development framework for PHP that provides an


extensible architecture for developing, maintaining, and
deploying applications. Using commonly known design
patterns like MVC, CakePHP reduces development costs and
helps developers write less code.

 Current version (Stable: 1.2.0.7962 )

CakePhp@PhpRoR Solutions 3
Here’s a quick list of features you’ll enjoy when using CakePHP:

 Active, friendly community


 Flexible licensing
 Compatible with versions 4 and 5 of PHP
 Integrated CRUD for database interaction
 Application scaffolding
 Code generation
 MVC architecture
 Request dispatcher with clean, custom URLs and routes
 Built-in validation
 Fast and flexible templating (PHP syntax, with helpers)
 View Helpers for AJAX, JavaScript, HTML Forms and more
 Email, Cookie, Security, Session, and Request Handling Components
 Flexible ACL
 Data Sanitization
 Flexible Caching
 Localization
 Works from any web site directory, with little to no Apache configuration involved

CakePhp@PhpRoR Solutions 4
Components needed to run

cake
HTTP Server. Apache with mod_rewrite is preferred, but by no means
required.
 PHP 4.3.2 or greater. Yes, CakePHP works great on PHP 4 and 5.
 Technically a database engine isn’t required, but we imagine that most
applications will utilize one. CakePHP supports a variety of database
storage engines:
 MySQL (4 or greater)
 PostgreSQL
 Firebird DB2
 Microsoft SQL Server
 Oracle
 SQLite
 ODBC
 ADOdb

CakePhp@PhpRoR Solutions 5
Model-View-Controller
 CakePHP follows the MVC software design pattern.
Programming using MVC separates.
your application into three main parts:
 The Model represents the application data
 The View renders a presentation of model data
 The Controller handles and routes requests made by the
client

CakePhp@PhpRoR Solutions 6
Some Extra
 CakePHP features Controller, Model, and View classes, but it

also features some additional classes and objects that

make development in MVC a little quicker and more

enjoyable. Components, Behaviors, and Helpers are classes

that provide extensibility and reusability to quickly add

functionality to the base MVC classes in your applications.

CakePhp@PhpRoR Solutions 7
Directory structure
 /var/www/html
– /cake_1_2
 /app
– /config
– /controllers
– Models
– Views
– webroot
 /cake
 /vendors
 /.htaccess
 /index.php
 /README

CakePhp@PhpRoR Solutions 8
Convention - Filename
 Controller
– UsersController -> users_controller.php

– TaskStatusesController->task_statuses_controller
 Model
– Users -> user.php

– task_statuses->task_status.php

CakePhp@PhpRoR Solutions 9
Controller
 A controller is used to manage the logic for a part of your
application. Most commonly, controllers are used to manage the
logic for a single model.
 For example, if you were building a site for an Task Management
System, you might have a UsersController and a ProjectsController
managing your users and projects. In CakePHP, controllers are
named after the model they handle, in plural form.
 Your application's controllers are classes that extend the CakePHP
AppController class, which in turn extends a core Controller class.
 Controllers can include any number of methods which are usually
referred to as actions. Actions are controller methods used to
display views. An action is a single method of a controller.
CakePHP’s dispatcher calls actions when an incoming request
matches a URL to a controller’s action.

CakePhp@PhpRoR Solutions 10
Controller (cont.)
For example
our UsersController might contain the view(), add(), and
index() actions. The controller would be found in
/app/controllers/users_controller.php and contain:

class UsersController extends AppController {

var $name = 'Users';


}

 The $name attribute should be set to the name of the


controller.

CakePhp@PhpRoR Solutions 11
Components
 Components are packages of logic that are shared between
controllers.
 CakePHP also comes with a fantastic set of core
components you can use to aid in:

CakePhp@PhpRoR Solutions 12
Components (cont.)
class UsersController extends AppController {

var $name = 'Users';


var $components = array(‘Session‘,’Auth’);

function logout() {
$this->Session->setFlash('Successfully Logout...');
$this->redirect($this->Auth->logout());
}
}

CakePhp@PhpRoR Solutions 13
Model
Models represent data and are used in CakePHP applications
for data access. A model usually represents a database table
Here is a simple example of a model definition in CakePHP:

class User extends AppModel {


var $name = 'User';
}

With your model defined, it can be accessed from within your


Controller. CakePHP will automatically make the model
available for access when its name matches that of the
controller. For example, a controller named UsersController
will automatically initialize the Ingredient model and attach it
to the controller at $this->User.

CakePhp@PhpRoR Solutions 14
Model (cont.)
class UsersController extends AppController {
var $name = 'Users';
}

Function index() {
$this->set('users',$this->User->find('all'));
}

CakePhp@PhpRoR Solutions 15
Associations: Linking Models
Together
 Defining relations between different objects in your
application should be a natural process. For example: in a
tasks database, a task may have many users, tasks have a
single project, and projects may have many tasks.
 The four association types in CakePHP are: hasOne,
hasMany, belongsTo, and hasAndBelongsToMany

CakePhp@PhpRoR Solutions 16
class User extends AppModel {

var $name = 'User';


var $belongsTo = array(
'Group' => array('className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => '‘ )
);
}

CakePhp@PhpRoR Solutions 17
Model Attributes
 validate
This attribute holds rules that allow the model to make data
validation decisions before saving. Keys named after fields
hold regex values allowing the model to try to make
matches.

For example:
class User extends AppModel {
var $name = 'User';

var $validate = array(


'id' => array('notempty'),
'username' => array('notempty'),
'password' => array('notempty'),
'email' => array('email'),
'first_name' => array('notempty'),
'last_name' => array('notempty')
); }
CakePhp@PhpRoR Solutions 18
Behaviours
 Behaviors add extra functionality to your models. CakePHP
comes with a number of built-in behaviors such as Tree and
Containable.
 CakePHP already includes behaviors for tree structures,
translated content, access control list interaction
 Behaviors are attached to models through the $actsAs
model class variable:
class Users extends AppModel {
var $name = ‘User';
var $actsAs = array(‘ACL');
}

CakePhp@PhpRoR Solutions 19
Views
 The view layer of CakePHP is how you speak to your users.
Most of the time your views will be showing (X)HTML
documents to browsers,
 CakePHP view files are written in plain PHP and have a
default extension of .ctp (CakePHP Template). These files
contain all the presentational logic needed to get the data it
received from the controller in a format that is ready for the
audience you’re serving to.
 View files are stored in /app/views/, in a folder named after
the controller that uses the files, and named after the
action it corresponds to. For example, the view file for the
Users controller's "view()" action, would normally be found
in /app/views/users/view.ctp.

CakePhp@PhpRoR Solutions 20
The view layer in CakePHP can be made up of a number of
different parts.
 layouts: A layout contains presentation code that wraps
around a view. Anything you want to see in all of your
views should be placed in a layout.
 elements: Many applications have small blocks of
presentation code that needs to be repeated from page
to page, sometimes in different places in the layout.
CakePHP can help you repeat parts of your website that
need to be reused. These reusable parts are called
Elements. Ads, help boxes, navigational controls, extra
menus, login forms, and callouts are often implemented
in CakePHP as elements. An element is basically a mini-
view that can be included in other views, in layouts, and
even within other elements. Elements can be used to
make a view more readable, placing the rendering of
repeating elements in its own file. They can also help you
re-use content fragments in your application.

CakePhp@PhpRoR Solutions 21
 helpers: these classes encapsulate view logic that is
needed in many places in the view layer. Among other
things, helpers in CakePHP can help you build forms,
build AJAX functionality, paginate model data, or serve
RSS feeds.
Helpers are the component-like classes for the
presentation layer of your application. They contain
presentational logic that is shared between many views,
elements, or layouts.
Core Helpers:
 AJAX, Cache, Form, HTML, Javascript, Number, Paginator,
RSS, Session, Text, Time, XML

CakePhp@PhpRoR Solutions 22
HtmlHelp

er
The role of the HtmlHelper in CakePHP is to make HTML-
related options easier, faster, and more resilient to change.

<?php echo $html->link('Enter', '/pages/home',


array('class'=>'button')); ?>

FormHelpe
r
 The FormHelper is a new addition to CakePHP. Most of the
heavy lifting in form creation is now done using this new
class, rather than (now deprecated) methods in the
HtmlHelper.
<?php echo $form->create('Recipe'); ?>
 echo $form->input('username'); //text
 echo $form->input('password'); //password
CakePhp@PhpRoR Solutions 23
Scaffolding
 Application scaffolding is a technique that allows a developer to
define and create a basic application that can create, retrieve,
update and delete objects. Scaffolding in CakePHP also allows
developers to define how objects are related to each other, and to
create and break those links.
 CakePHP’s scaffolding is pretty cool. It allows you to get a basic
CRUD application up and going in minutes.
 Scaffolding is a great way of getting the early parts of developing
a web application started.
 This has a downside: a web developer hates creating forms that
never will see real use. To reduce the strain on the developer,
scaffolding has been included in CakePHP. Scaffolding analyzes
your database tables and creates standard lists with add, delete
and edit buttons, standard forms for editing and standard views
for inspecting a single item in the database.

CakePhp@PhpRoR Solutions 24
Scaffolding (cont.)
 To add scaffolding to your application, in the controller, add
the $scaffold variable:

<?php
class CategoriesController extends AppController {
var $scaffold;
}
?>

CakePhp@PhpRoR Solutions 25
The CakePHP Console
[introduction into CakePHP at the command-line. ]

CakePhp@PhpRoR Solutions 26
Code Generation with

Bake
The Bake console can create any of CakePHP’s basic
ingredients: models, views and controllers.
 Bake can create a fully functional application in just a few
minutes. In fact, Bake is a natural step to take once an
application has been scaffolded.

running Bake will present you with the following options:

CakePhp@PhpRoR Solutions 27
Plugins
 CakePHP allows you to set up a combination of controllers,
models, and views and release them as a packaged
application plugin that others can use in their CakePHP
applications.
 The main tie between a plugin and the application it has
been installed into, is the application's configuration
(database connection, etc.). Otherwise, it operates in its
own little space, behaving much like it would if it were an
application on its own.
 Once a plugin has been installed in /app/plugins, you can
access it at the URL /pluginname/controllername/action.
 For example:
http://theguru/vikas/blog/posts/chat

CakePhp@PhpRoR Solutions 28
Thanks….

CakePhp@PhpRoR Solutions 29

You might also like