Pages

Showing posts with label cakephp. Show all posts
Showing posts with label cakephp. Show all posts

Friday, September 5, 2014

Cakephp-Overview of Programming Patterns

Active Record Pattern

Active Record Pattern is for those application's which use relational databases.
The interface of an object conforming to this pattern would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table.

Association Data Mapping

An Association data mapping pattern allows Relational object to associate with other Relational Objects the way they are associated in Relational Databases.

Front Controller

The Front Controller Pattern allows handling of all requests to be at a centralized location from where they are redirected specified Request Processors.

MVC

MVC expended as Model View Controller is a pattern where

Model's act as a wrapper classes for Database Table's
Controller's act as wrapper classes for Business Logic
and View act's as file for User Interface
 

Wednesday, September 11, 2013

cakephp-requestAction

The method requestAction are used in cake php for calls a controller’s action from any location and returns data from the action.

Example :

 // Controller/CommentsController.php  
 class CommentsController extends AppController {  
   public function latest() {  
     if (empty($this->request->params['requested'])) {  
       throw new ForbiddenException();  
     }  
     return $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));  
   }  
 }  

 // View/Elements/latest_comments.ctp  
 $comments = $this->requestAction('/comments/latest');  
 foreach ($comments as $comment) {  
   echo $comment['Comment']['title'];  
 }  

Cakephp-Difference in App:Uses(),App::import(),App::path()

App::uses() loads libraries using same standrds as cakephp folder structure i.e for files which follow the same standards regarding folder and file naming.

This is why it is not advisable to load vendor's using App::uses().

App::import() loads file if it has not been included before i.e. it is just a wrapper of include_once();

App::path() return the path of concerned cakephp folder

example: App::path('Vendor') return's path of vendor

Drawbacks of cakephp

1. Can't be used for small scale apps as it loads the complete application in beginning.
2. Learning Curve

Cakephp-Why cakephp have two vendor folder?

The “vendors” folder in the “app” folder is for application-specifc third-party libraries whereas the other “vendors” folder is for libraries you want to use in multiple applications.

Cakephp-What are cakephp's configuration files?

  1. /app/config/core.php=>where we manage core configuration's such as debug,use of .htaccess
  2. /app/config/database.php=>Manage database configurations
  3. /app/config/email.php=>Manage email smtp configurations
  4. /app/config/routes.php=>manage routing

Cakephp-What are commonly used components of cakephp?

1. Security
2. Sessions
3. Access control lists
4. Emails
5. Cookies
6. Authentication
7. Request handling

Cakephp-What is the naming convention in cakephp

  1. Table names are plural and lowercased
  2. Model names are singular and CamelCased: ModelName, model filenames are singular: model.php
  3. Controller names are plural and CamelCased with *Controller* appended: ControllerNamesController, controller filenames are named similerly : usersController
  4. Associations should use the ModelName, and the order should match the order of the foreignKeys: var $belongsTo = ‘User’; 
  5. Foreign keys should always be: table_name_in_singular_form_id: user_id (foreign key) → users (table),
  6. many-to-many join tables should be named: alphabetically_first_table_plural_alphabetically_second_table_plural: tags_users ,
  7. columns in many-to-many join tables should be named like other foreign keys: tag_id and user_id ,
  8. columns named “created” and “modified” will automatically be populated correctly

Sunday, February 3, 2013

Constants,Configuration Variables in cake php

Many a times we need to use some variables throughout our application.

CakePHP's Configure class can be used to store and retrieve application or runtime specific values. This class can be used to store anything and can be accessed from any part of the application

For the application of the same we define a file in app/config/config.php

To store a configuration variable:

Configure::write('variable_name', 'value') ;

And to read from configuration:
 
Configure::read('variable_name');

Now we can use Configure::write() or we can also use the $config array

as follows

// Create the config array
$config = array();


// Define config variable
$config['from_email'] = '';


//  Or Define variable as follows

Configure::write('from_email', 'abc@abc.com') ;

 
$config['api_key'] = 'http://www.example.com';
$config['default_timezone'] = 'Europe/London'; 
$config['page_limit'] = 6;


Now our Framework must know about this file so add the following code in /app/config/bootstrap.php

Configure::load('config');


Now read the configuration variables anywhere in the application as follows

Configure::read('from_email');
Configure::read('api_key');
Configure::read('page_limit');
 

Sunday, January 27, 2013

Cakephp Auth Component 2.0

Cakephp Auth Component 2.0

Define Auth component to controller as follows

public  $comonents=array(
'Auth'=>array(
                           'loginRedirect' =>array('controller'=>'users','action'=>'index'),
                           'logoutRedirect'=>array('controller'=>'users','action'=>'index'),
                            'authError'=>'Access Denied',
                            'authorize'=>array('Controller'),
                            'loginError'=>'Invalid credentials, please try again.',
                            'allow'=>('index','view');
                       ) ,
'Session'
);

//check for authorization
public function isAuthorized($user)
{
          return true;
}

Now in users controller define the login action

public function login()
{
       if($this->Auth->login())
       {
           $this->redirect($this->Auth->redirect());
       }
     else
    {
       $this->Session->setFlash('Authentication Failed')
   }
}

public function logout()
{
     $this->redirect($this->Auth->logout());
}

create form in login view to provide interface to user for username and password and AuthComponent will automatically validate login.

Make sure fields in the database match cake's cretriea i.e "usename" for User Name and "password" for Password and "Users" table.

register new user 
create a new add method in a controller create a view for the same and then in user model just before save hash the password as follows

$this->data['user']['password']=AuthComponent::password($this->data['User']['Password']);

To check for login status
$this->Auth->loggedIn();
To get current info of loggedin user
 $this->Auth->User;
To Display auth error message
$this->Session->flash('auth');

Scaffolding in Cakephp

Application scaffolding is a technique that allows a developer to define and create a basic application that can create, retrieve, update and delete objects.

To add scaffolding to your application, in the controller, add the $scaffold variable.

class CategoriesController extends AppController {
    var $scaffold;
}

Scaffolding a way to automatically look at what a table has and its very basic front end to check its CRUD Operations

Scaffolding automatically reads relations defined in a model

Foe example if your table has a field of tinyint attribute with length 1 then in that case cakephp will treat the same as a checkbox.

When we use a "hasMany" relation in a Model the form will show a dropdown

When we use a "has and belongs to Many" relation in a Model the form will show a multiselect list box

When we use a "belongsTo" relation in a Modelthe form will show a dropdown

The Scaffolding Structure(Form in view) shows the relation with an "Alias Name" given for the relation defined in a model.

Foe example if we have define a Table "Persons" and another table as "Horses" then we define the relation in a "Horses" model as

var $belongsTo=array('Owner'=>array('classname'=>'Person','foriegnKey'=>'owner_id'))

then Scaffolding for the  model will show the field name for owner_id as Owner.

also for a case like

var $hasAndBelongsToMany=array('Riders'=>array('className'=>'Person'));

and in Persons model we define

var $hasAndBelongsToMany=array('Horse');

we will find a multiselect list box with name "Riders" with automatically picked up names from Persons table.


Friday, January 25, 2013

First file that gets loaded on using cakephp?Is it changable?

Bootstrap.php , yes it can be changed , either through index.php , or through .htaccess

Why cakephp then any other framework?

Why cakephp then any other framework?

Well, This might not be the perfect answer but I state it as follows

*Has been for years in the market with strong support in the form of communities and online documentation
*It supports PHP 4 and 5 , sometimes it becomes mandatory to support PHP 4 because of client's limitation in support PHP 5, there cakephp helps.

To be frank I had worked on Yii and Cakephp and the only difference I found was this however my further analysis stated that CI and Kohana also support PHP4.

Though every framework has its critics for example In cakephp if it supports PHP 4 OOPS the "privates can be accessed easily".

But since the question was positive and so was the answer.


What is Cakephp

What is Cakephp?
Cakephp is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. 
It uses commonly known design patterns like MVC,ORM within the convention over configuration paradigm.
It also reduces development costs and helps developers write less code.

MVC=>MODEL VIEW CONTROLLER
ORM =>OBJECT RELATION MAPPING

ORM stands for a technique in which we turn every RELATION(Table) into an OBJECT and its ATTRIBUTES as data members of the class.

*If you are familiar with Entity framework in .Net consider the Db Context class which represents a database
*In regular MVC Model classes are created to represent Tables of the concerned database.

Friday, December 7, 2012

Interview Question on relations in cakephp

Recently I was asked on different types of relations in between models in a cakephp framework

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.

Then I was given 4 tables as follows

Employee:
Eid,fname,lname

Department:
Deptid,deptname

Salary: 
Sid,salary

EmpSalDeptrelation:
eid,sid,deptid

To these I was told to determine how relations will be represented in EmpSalDeptrelation table so that if I fetch 1 employee I get his salary department along

Answer is to the EmpSalDeptrelation model add the relationships as

eid belongsTo Eid of employee,sid belongs to Sid of salary,deptid belongs to Deptid of Department

and then in the respective controller which uses($uses) this model
add
$this->empsaldeptrelation->find();
set the conditions where eid equaks to concerned employee id;