Thursday, 5 February 2015

Beginning Cake PHP

Beginning Cake PHP 

CakePHP

CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. CakePHP goal is to enable developers to work in a structured and rapid manner–without loss of flexibility. CakePHP takes the monotony out of web development.





Figure 1
 

MVC in CakePHP

Model view controller (MVC) is an architectural pattern used in software engineering.
Model: Database functions exist in the model
View: Design parts written here
Controller: Business Logic goes here

Database related functions

find, findAll , findAllBy , findBy , findNeighbours and query.

Security.salt and Security.cipherSeed in cakephp

- The Security.salt is used for generating hashes.we can change the default Security.salt value in /app/Config/core.php.  
- The Security.cipherseed is used for encrypt/decrypt strings.We can change the default Security.cipherSeed value by editing /app/Config/core.php. 

First file that gets loaded when you run a application

bootstrap.php
yes it can be changed.Either through index.php , or through .htaccess

Naming convention

Table names are plural and lowercased

model names are singular and CamelCased: ModelName, model filenames are singular and underscored: model_name.php, 

controller names are plural and CamelCased with *Controller* appended: ControllerNamesController, controller filenames are plural and underscored with *controller* appended: controller_names_controller.php,

Models

 Models are the classes that form the business layer in your application. They should be responsible for managing almost everything regarding your data, its validity, and its interactions, as well as the evolution of the information workflow in your domain.
More on models

Behavior

Behaviors in CakePHP are associated with Models.
Behaviors are used to change the way models behaves and enforcing model to act as something else.

Containable
Containable behavior

Relationship Types

The four association types in CakePHP are: hasOne, hasMany, belongsTo, and hasAndBelongsToMany (HABTM).

Relationship Association Type Example
one to one hasOne A user has one profile.
one to many hasMany A user can have multiple recipes.
many to one belongsTo Many recipes belong to a user.
many to many hasAndBelongsToMany Recipes have, and belong to, many ingredients.

 

Model Callcacks

beforeFind
beforeFind(array $query)  ::  Called before any find-related operation. The $query passed to this callback contains information about the current query: conditions, fields, etc.

afterFind
afterFind(array $results, boolean $primary = false)  ::Use this callback to modify results that have been returned from a find operation, or to perform any other post-find logic. The $results parameter passed to this callback contains the returned results from the model’s find operation

beforeValidate
beforeValidate(array $options = array())   ::  Use this callback to modify model data before it is validated, or to modify validation rules if required. This function must also return true, otherwise the current save() execution will abort.

afterValidate
afterValidate()  ::  Called after data has been checked for errors. Use this callback to perform any data cleanup or preparation if needed.

beforeSave
beforeSave(array $options = array())   ::   Place any pre-save logic in this function. This function executes immediately after model data has been successfully validated, but just before the data is saved. This function should also return true if you want the save operation to continue.
This callback is especially handy for any data-massaging logic that needs to happen before your data is stored. If your storage engine needs dates in a specific format, access it at $this->data and modify it.

afterSave
afterSave(boolean $created, array $options = array())   ::  If you have logic you need to be executed just after every save operation, place it in this callback method. The saved data will be available in $this->data.
The value of $created will be true if a new record was created (rather than an update).
The $options array is the same one passed to Model::save().

beforeDelete
beforeDelete(boolean $cascade = true)   ::  Place any pre-deletion logic in this function. This function should return true if you want the deletion to continue, and false if you want to abort.

afterDelete
afterDelete()  ::      Place any logic that you want to be executed after every deletion in this callback method.
// perhaps after deleting a record from the database, you also want to delete // an associated file public function afterDelete() { $file = new File($this->data['SomeModel']['file_path']); $file->delete(); }
 
onError
onError()   ::   Called if any problems occur.

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. 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.
default function in controller is index() function

Callbacks

Main call back functions are,
Controller::beforeFilter()         
           This function is executed before every action in the controller. It’s a handy place to check for an active session or inspect user permissions.
Controller::beforeRender()
Called after controller action logic, but before the view is rendered. This callback is not used often, but may be needed if you are calling render() manually before the end of a given action.
Controller::afterFilter()
Called after every controller action, and after rendering is complete. This is the last controller method to run.
The render() method is automatically called at the end of each requested controller action. This method performs all the view logic (using the data you’ve submitted using the set() method), places the view inside its $layout, and serves it back to the end user.
 
Example:
class RecipesController extends AppController { 
        // ...  
   public function search() {  
           // Render the view in /View/Recipes/search.ctp $this->render();  
    }  
        // ... 
}

Flow Control

redirect(mixed $url, integer $status, boolean $exit)

$this->redirect(array('controller' => 'orders', 'action' => 'thanks'));
$this->redirect('/orders/thanks'); $this->redirect('http://www.example.com');
$this->redirect(array('action' => 'edit', $id));  
$this->redirect($this->referer());

$this->redirect(array( 'controller' => 'orders', 'action' => 'confirm', 'product' => 'pizza', 'quantity' => 5) );  

 O/P http://www.example.com/orders/confirm/product:pizza/quantity:5 

$this->redirect(array( 'controller' => 'orders', 'action' => 'confirm', '?' => array( 'product' => 'pizza', 'quantity' => 5 ), '#' => 'top') );   

O/P http://www.example.com/orders/confirm?product=pizza&quantity=5#top 

flash(string $message, string|array $url, integer $pause, string $layout)
method is different in that it shows a message before passing t
he user on to another URL. 

Accessing request parameters

//Route Elements
$this->request->controller; $this->request['controller'];  
$this->request->params['controller'];

// Passed arguments  
$this->request->pass;  
$this->request['pass'];  
$this->request->params['pass'];  

// named parameters 
$this->request->named;  
$this->request['named']; 
$this->request->params['named'];

 

Accessing Querystring parameters

// URL is /posts/index?page=1&sort=title  
$this->request->query['page'];  

// You can also access it via an array
$this->request['url']['page']; 
 

Accessing POST data

$this->request->data['MyModel']['title'];
  • $this->request->webroot contains the webroot directory.
  • $this->request->base contains the base path.
  • $this->request->here contains the full address to the current request.
  • $this->request->query contains the query string parameters.

$this->set()  --> method is used for creating a variable in the view file
 
     For example,
        1.  $this->set('posts',$posts);
        2.   $this->set('color', 'pink');  //in controller 
            <?php echo $color; ?>   // in view
 

$this->set(compact()) --> can pass multiple parameters to access into the view file.
      For example,
       $this->set(compact('posts','users','reports'));

 

Components

Components are packages of logic that are shared between controllers.
They are useful when a common logic or code is required between different controllers.
Commonly used components
1. Security
2. Sessions
3. Access control lists
4. Emails
5. Cookies
6. Authentication
7. Request handling

class PostsController extends AppController {  
public $components = array('Session', 'Cookie');  
public function delete() { 
 if ($this->Post->delete($this->request->data('Post.id')) {  
     $this->Session->setFlash('Post deleted.');  
     return $this->redirect(array('action' => 'index'));  
}

OR
public $components = array(‘Emails’, ‘ImageUploader’, ‘Sms’);

Scaffolding

Scaffolding is a set of automatic actions for starting web development work faster.
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

<?php
class PostsController extends AppController {
    var $scaffold;
}
?>
Assuming you’ve created Post model class file (in /app/Model/post.php), you’re ready to go. Visit http://example.com/posts to see your new scaffold. 

View

 Views are responsible for generating the specific output required for the request. Often this is in the form of HTML, XML, or JSON, but streaming files and creating PDF’s that users can download are also responsibilities of the View Layer.

$this->Html->script('carousel', array('inline' => false));  
$this->Html->css('carousel', array('inline' => false));

 // app/View/Common/view.ctp  

<h1><?php echo $this->fetch('title'); ?></h1>  
<?php echo $this->fetch('content'); ?>  
<div class="actions"> <h3>Related actions</h3>  
            <ul> <?php echo $this->fetch('sidebar'); ?> </ul>  
</div>

Helpers


Helpers in CakePHP are associated with Presentation layers of application.
Helpers mainly contain presentational logic which is available to share between many views, elements, or layouts

A helper is used for helping cakephp in rendering the data to be shown to user with views(Eg Form, HTML etc).
public $helpers = array(‘Form’, ‘Html’, ‘Js’, ‘Time’);
to in specific action use below code in that action
$this->helper[] =”helper_name”;

Element

Element in cakephp are smaller and reusable bits of view code. Elements are usually rendered inside views.

 

layout

Layout in cakephp are used to display the views that contain presentational code. In simple views are rendered inside a layout

 

Set layout in the controller

var $layout = ‘layout_name’;
to overwrite for a specific action use below code in that action
$this->layout =”layout_name”;

 

Include helpers in controller

public $helpers = array(‘Form’, ‘Html’, ‘Js’, ‘Time’);
to in specific action use below code in that action
$this->helper[] =”helper_name”;

 

Include components in controller

public $components = array(‘Emails’, ‘ImageUploader’, ‘Sms’);

 

Difference between Component, Helper, Behavior

Component is a Controller extension.
Helpers are View extensions.
Behavior is a Model Extension.

Difference between required and notEmpty in cakephp?

To understand this question read this post:

 

$this->set(); when used in the Controller actions

The set() method is used to create a variable in the view file. In the example above, the variable $articles will then be available to use in the view template file for that action.
An advantage of the first example (i.e., $this->set('articles', $articles); is that it allows the variable name on the view to be different from the variable name on the controller. For example, if you wanted them to be different, you could do something like $this->set('articlesData', $articles);. The variable on the view file would then be $articlesData.
The advantage of the second approach (i.e., $this->set(compact('articles'));, on the other hand, is that it is somewhat neater, and it also is arguably a bit less error-prone. It is also shorter and easier to write, especially where we are setting several variables to the view.

 

Get current URL in CakePHP

To get current url in cakephp use, 
echo Router::url($this->here, true);
This will give full URL with hostname.If you want to get relative path instead of full URL,then use the following code:
echo $this->here;
This will produce absolute URL excluding hostname i.e. /controller/abc/xyz/

 

Methods are used to create and destroy model associations on the fly

The bindModel() and unbindModel() Model methods are used to create and destroy model associations on the fly.

 

Using cakephp, what all are drawbacks.

it loads full application before it starts your task. Its not recommended for small projects because of its resource heavy structure.
 



For references :-


Detailed
Cake php started at april 2005.When a Polish programmer Michal Tatarynowicz wrote a minimal version of a Rapid Application Framework in PHP, dubbing it Cake.Cake php version 1.0 released in May 2006.
2.5.4  released on 2014-09-02.
Server requirements
Here are the requirements for setting up a server to run CakePHP:
An HTTP server (like Apache) with the following enabled: sessions, mod_rewrite (not absolutely necessary but preferred)
PHP 4.3.2 or greater. Yes, CakePHP works great in either PHP 4 or 5.
A database engine (right now, there is support for MySQL 4+, PostgreSQL and a wrapper for ADODB).
Installation
step1: Go to cakephp.org and download the latest version of cakephp.
step2: Cakephp comes in a .zip file,so unzip it.
step3: Extract the files in the localhost in the desired folder (for example:cakephp).
step4: Open the browser and run the URL localhost/cakephp
step5: Just Follow the instructions display on the page.

Wednesday, 4 February 2015

Baking CakePHP in ubuntu


Baking CakePHP in ubuntu

Step1

download  CakePHP file and paste where you want
for example
i have placed in mycomputer/opt/lampp/htdocs/foldername
i am using Linux system

Step2 
Give read and write permission to tmp folder


Step3 
Create database and tables for your application
configure your application with database i.e.  app/config/database.php
change password and salt password in app/config/core.php

Step4

path name should be like this

user@dreamphp:/opt/lampp/htdocs/cakephpbake/app/Console$ 
 
(cakephpbake--> folder_name)

Step5

next step copy and run this cmd prompt

sudo apt-get install cakephp-scripts 

Step6

password of system have to give

[sudo] password for user: ******
Reading package lists... Done

//result displayed given below.. for references 
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
apache2 apache2-bin apache2-data cakephp libapache2-mod-php5
libaprutil1-dbd-sqlite3 libaprutil1-ldap php5 php5-cli php5-common php5-json
php5-readline


Suggested packages:
apache2-doc apache2-suexec-pristine apache2-suexec-custom apache2-utils
cakephp-instaweb php5-mysql php-pear php5-user-cache
The following NEW packages will be installed:
apache2 apache2-bin apache2-data cakephp cakephp-scripts libapache2-mod-php5
libaprutil1-dbd-sqlite3 libaprutil1-ldap php5 php5-cli php5-common php5-json
php5-readline


0 upgraded, 13 newly installed, 0 to remove and 136 not upgraded.
Need to get 6,885 kB of archives.
After this operation, 32.0 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

Y
 

After that installation process.. it will take 10 to 20 mins
//result displayed given below.. for references
Get:1 http://in.archive.ubuntu.com/ubuntu/ trusty/main php5-json i386 1.3.2-2build1 [34.2 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu/ trusty-updates/main php5-common i386 5.5.9+dfsg-1ubuntu4.5 [443 kB] 


Step7
Here you are setting database through cmd prompt

user@dreamphp:/opt/lampp/htdocs/cakephpbake/app$ cake bake all


//result displayed given below.. for references
---------------------------------------------------------------
The following database configuration will be created:
---------------------------------------------------------------
Name:         default
Driver:       mysql
Persistent:   true
Host:         host_name
User:         user_name
Pass:        
Database:     database_name
---------------------------------------------------------------
 Creating file /opt/lampp/htdocs/cakephpbake/app/myapp/config/database.php
Wrote `/opt/lampp/htdocs/cakephpbake/app/myapp/config/database.php`

Step8

if you want to create new folder and should execute in that folder means use Step8 other wise skip this step

user@dreamphp:/opt/lampp/htdocs/cakephpbake/app$ cake bake 

//result displayed given below.. for references
Welcome to CakePHP v1.3.14 Console
---------------------------------------------------------------
App : app
Path: /opt/lampp/htdocs/cakephpbake/app
---------------------------------------------------------------
What is the full path for this app including the app directory name?
 Example:/opt/lampp/htdocs/cakephpbake/app/myapp 
[/opt/lampp/htdocs/cakephpbake/app/myapp] > 

 opt/lampp/htdocs/cakephpbake/app/myapp 

Step9

You can skip if you skip 8th step

next have check path is in myapp if not give
cd myapp

user@dreamphp:/opt/lampp/htdocs/cakephpbake/app/myapp$ cake bake

//result displayed given below.. for references 

Welcome to CakePHP v1.3.14 Console
---------------------------------------------------------------
App : myapp
Path: /opt/lampp/htdocs/cakephpbake/app/myapp
---------------------------------------------------------------
Interactive Bake Shell
---------------------------------------------------------------
[D]atabase Configuration
[M]odel
[V]iew
[C]ontroller
[P]roject
[F]ixture
[T]est case
[Q]uit
What would you like to Bake? (D/M/V/C/P/F/T/Q)


m

[[[[[[[[
I got an error like fatal error mysql_query() not fount
i added  

PATH=/opt/lampp/bin:$PATH 

in home->.bashrc file 
and restart your apache ]]]]]



//result displayed given below.. for references 

---------------------------------------------------------------
Bake Model
Path: /opt/lampp/htdocs/cakephpbake/app/myapp/models/
---------------------------------------------------------------
Possible Models based on your current database:
1. Category
2. Job
3. OrderInfo
4. Product
5. User
Enter a number from the list above,
type in the name of another model, or 'q' to exit
[q] > 1
Would you like to supply validation criteria
for the fields in your model? (y/n)
[y] >y


Field: id
Type: integer
---------------------------------------------------------------
Please select one of the following validation options:
---------------------------------------------------------------
1 - alphanumeric
2 - between
3 - blank
4 - boolean
5 - cc
6 - comparison
7 - custom
8 - date
9 - decimal
10 - email
11 - equalto
12 - extension
13 - inlist
14 - ip
15 - maxlength
16 - minlength
17 - money
18 - multiple
19 - notempty
20 - numeric
21 - phone
22 - postal
23 - range
24 - ssn
25 - time
26 - url
27 - userdefined
28 - uuid
29 - Do not do any validation on this field.
... or enter in a valid regex validation string.


Would you like to add another validation rule? (y/n)
[n] >
Would you like to define model associations
(hasMany, hasOne, belongsTo, etc.)? (y/n)
[y] > y
One moment while the associations are detected.
---------------------------------------------------------------
Please confirm the following associations:
---------------------------------------------------------------
Category hasMany Job? (y/n)

[y] >
Would you like to define some additional model associations? (y/n)
[n] > y
What is the association type?
1. belongsTo
2. hasOne
3. hasMany
4. hasAndBelongsToMany
Enter a number











Monday, 2 February 2015

CakePHP installing and Making a small application

Downloading CakePHP

https://github.com/cakephp/cakephp/tags
OR
http://cakephp.org/

download the file and place it in working folder ie, 
in windows
drive/wamp/www/place_folder(eg: cakephp)
in linux
/opt/lampp/htdocs/cakephp

Naming Conventios

Table names are plural and lowercased .

model names are singular and CamelCased: ModelName, model filenames are singular and underscored: model_name.php .

controller names are plural and CamelCased with *Controller* appended: ControllerNamesController, controller filenames are plural and underscored with *controller* appended: controller_names_controller.php  .

Give permission to folder

HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
setfacl -R -m u:${HTTPDUSER}:rwx app/tmp
setfacl -R -d -m u:${HTTPDUSER}:rwx app/tmp 

Getting Start with CakePHP

folder structure
/cakephp(my_foler_name)
    /app
             /congig
             /controller
             /model
             /view
             /temp
             /lib                //less folder only given
    /lib
    /plugins
    /vendors
    .htaccess
    index.php
    README 

CakePHP database configration

/app/Config/database.php.default. Make a copy of this file in
the same directory, but name it database.php.
 
cakephp/app/Config/database.php (if database.php is not there create new file) 
public $default = array(
 'datasource' => 'Database/Mysql',
 'persistent' => false,
 'host' => 'localhost',                        //hostname
 'port' => '',
 'login' => 'root',                                //username
 'password' => '',                              //password
 'database' => 'cakephp',               //database name
 'schema' => '',
 'prefix' => '',
 //'encoding' => 'utf8',
);

Creating database

First we will create a table in our database for example:
CREATE TABLE `categories` (
  `id` INTEGER(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM
>>   table names are in plural 

Creating Model for table

1. create a model for the table `categories`
2. path  >>   /app/model/Category.php
Example code
<?php
class Category extends AppModel {
    var $name = 'Category';
}
?>
>> naming convention for models is that file and class names are in singular
explanation:
extended CakePHP’s AppModel class and declared a variable $name which will be used from our Controller to access the model’s functions.

Creating Controller

1. path >>  /app/controllers/CategoriesController.php
 
 Example code
<?php
class CategoriesController extends AppController {

    var $name = 'Categories';
    public $helpers = array('Html', 'Form');

    function index() {
        $this->set('categories', $this->Category->find('all'));
    }
}
?>
 explanation:
>>  We are extending AppController class, declaring $name variable.
>>  added function called index(). The controller functions are called actions
>> 'categories'  table name
>>  By defining function index() in our CategoriesController, users can now access the logic there by requesting www.example.com/categories/index or in localhost  >> localhost/categories/index
>>  $this->set('categories', $this->Category->find('all')); 
This is to selecting all categories from categories table and assigning the resulting array to categories variable. This variable will be available in our index view 
>>  plural controller names.

Creating routes

create readable, understandable action names. You can map URLs to your code

Creating View

create folder Categories this folder name controller name case sensitive.
1. path >>  /app/views/Categories/index.ctp
2. Create a file index.ctp in /app/views/Categories/index.ctp , Ctp(CakeTemplatePHP) files are CakePHP template files.
 references http://book.cakephp.org/2.0/en/views.html#view-templates
 Example code
<h1>Categories</h1>
<?php echo $this->Html->link('Add Category',array('controller' => 'categories', 'action' => 'add')); ?>
<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
    </tr>
    <?php foreach ($categories as $category): ?>
    <tr>
        <td><?php echo $category['Category']['id']; ?></td>
        <td>
            <?php echo $this->Html->link($category['Category']['name'],
array('controller' => 'categories', 'action' => 'view', $category['Category']['id'])); ?>
        </td>
    </tr>
    <?php endforeach; ?>
</table>
 $html This code generates a link to /categories/view/category_id
 to run file http://localhost/cakephp/categories

Creating Add category

create add.ctp file inside  path >>  /app/views/Categories/index.ctp 

<!-- File: /app/views/categories/add.ctp -->       
<h1>Add Category</h1>
<?php
echo $this->form->create('Category');
echo $this->form->input('name');
echo $this->form->end('Save Post');
?>
create() --> If create() is called with no parameters supplied, it assumes you are building a form  that submits to the current controller’s add() action (or edit() action when id is included in the form data), via POST.
$form->input() --> used to create form elements of the same name.
         >  The first parameter tells  which field they correspond to
         >  second parameter allows to specify a wide array of options(number of rows for the  textarea)
echo $this->Form->input('password', array('type'=>'password'));
$form->end() -->  call generates a submit button and ends the form
 in controller 

<?php
class CategoriesController extends AppController {

    var $name = 'Categories';
     public $helpers = array('Html', 'Form');
    
    function index() {
        $this->set('categories', $this->Category->find('all'));
    }
    function add() {
        if (!empty($this->data)) {
            if ($this->Category->save($this->data)) {
                $this->Session->setFlash('Your category has been saved.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
}
?>
add in to view/Category/index.cpt
<?php echo $this->Html->link('Add Category',array('controller' => 'categories', 'action' => 'add')); ?>
the link to add category 

http://localhost/cakephp/categories