What is CakePHP 1.2
CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. Our primary goal is to enable you to work in a structured and rapid manner–without loss of flexibility.
CakePHP Directory Structure
After you've downloaded and extracted CakePHP, these are the files and folders you should see:
* app
* cake
* vendors
* plugins
* .htaccess
* index.php
* README
You'll notice three main folders:
* The app folder will be where you work your magic: it’s where your application’s files will be placed.
* The cake folder is where we’ve worked our magic. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core.
* Finally, the vendors folder is where you’ll place third-party PHP libraries you need to use with your CakePHP applications.
The App Folder
config: Holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.
controllers: Contains your application’s controllers and their components.
libs: Contains 1st party libraries that do not come from 3rd parties or external vendors. This allows you to separate your organization's internal libraries from vendor libraries.
locale: Stores string files for internationalization.
models: Contains your application’s models, behaviors, and datasources.
plugins: Contains plugin packages.
tmp: This is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions, logs, and sometimes session information.
Make sure that this folder exists and that it is writable, otherwise the performance of your application will be severely impacted. In debug mode, CakePHP will warn you if it is not the case.
vendors: Any third-party classes or libraries should be placed here. Doing so makes them easy to access using the App::import('vendor', 'name') function. Keen observers will note that this seems redundant, as there is also a vendors folder at the top level of our directory structure. We'll get into the differences between the two when we discuss managing multiple applications and more complex system setups.
views: Presentational files are placed here: elements, error pages, helpers, layouts, and view files.
webroot: In a production setup, this folder should serve as the document root for your application. Folders here also serve as holding places for CSS stylesheets, images, and JavaScript files.
How to use multiple databases in cake php ?
In this tutorial we will see how you can grab your data from different/multiple DB connections in the same application.
This is particularly usefull if you need to integrate your application with an existing system: let's immagine for example that your application needs to retrieve users data, and that the users data are shared by the general system you are integrating to in a different DB.
Let's get more real. The general application runs on a DB called DB_2, while your CakePHP application runs on DB_1. Users data are in DB_2, while all your app data are in DB_1.
First of all you need to specify 2 (or more DB connections) in app/config/database.php
class DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_1',
'password' => 'your_password_1',
'database' => 'DB_1',
'prefix' => ''
);
var $general_syst = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_2',
'password' => 'your_password_2',
'database' => 'DB_2',
'prefix' => ''
);
}
?>
By default CakePHP uses the 'default' connection in your models, if it exists in your database.php configuration.
An important thing is that if you use multiple DB connections in your models you should not set their connection as persistent: namely the 'persistent' key of your dB_connection array should be set to false.
This avoids that your application will use persistently the last connection you switched to in your models.
The key variable that will switch DB config in your models is: $useDbConfig
But let's build our User model and our Post model. They will respectively use:
* User model: general_syst connection
* Post model: default connection
User model (in app/models/user.php):
class User extends AppModel {
var $name = 'User';
var $useDbConfig = 'general_syst';
//your code here
//....
}
Post model (in app/models/post.php):
class Post extends AppModel {
var $name = 'Post';
var $useDbConfig = 'default';
//your code here
//....
}
In the Post model it wasn't really necessary to specify the $useDBconfig variable, because we CakePHP uses the 'default' DB config if nothing else is specified, but I specified it just to make the example clearer.
Right! Noe every time you will use in your controllers:
* $this->Post->bla_bla_bla : data will be retrieved/inserted/updated from DB_1
* $this->User->bla_bla_bla : data will be retrieved/inserted/updated from DB_2
Components in cake php ?
Suppose our online application needs to perform a complex mathematical operation in many different parts of the application. We could create a component to house this shared logic for use in many different controllers.
The first step is to create a new component file and class. Create the file in /app/controllers/components/math.php. The basic structure for the component would look something like this:
class MathComponent extends Object {
function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2;
}
}
?>
How to setup start up page in cakephp ?
in /app/config/routes.php
using this below line code to set the start up page in cakephp
Router::connect('/', array('controller' => 'users', 'action' => 'login', 'home'));
Helpers in cakephp ?
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.
CakePHP helpers i.e: Form, Html, JavaScript and RSS.
class BakeriesController extends AppController {
var $helpers = array('Form', 'Html', 'Javascript', 'Time');
}
?>
create a own helper:
class AwesomeHelper extends AppHelper {
function __construct($options = null) {
parent::__construct($options);
debug($options);
}
}
class AwesomeController extends AppController {
var $helpers = array('Awesome' => array('option1' => 'value1'));
}
What is GIT 1.7.0?
The management of changes to documents,programs,and other information stored as computer files
Benifits
1) Allows a team to share code
2) Miantain separate "production" versions of code that are always deployable
3) Allows simultaneous development of different features on the same codebase
4) keeps track of all old versions of files
5) Prevents work being overwritten
Behaviors in CakePHP
Model behaviors are a way to organize some of the functionality defined in CakePHP models. They allow us to separate logic that may not be directly related to a model, but needs to be there. By providing a simple yet powerful way to extend models, behaviors allow us to attach functionality to models by defining a simple class variable
Behaviors are attached to models through the $actsAs model class variable:
class Category extends AppModel {
var $name = 'Category';
var $actsAs = array('Tree');
}
?>
This example shows how a Category model could be managed in a tree structure using the TreeBehavior
class Category extends AppModel {
var $name = 'Category';
var $actsAs = array(
'Tree' => array(
'left' => 'left_node',
'right' => 'right_node'
),
'Translate'
);
}
?>
Let's say that on our previous Category model, which is acting as a Tree and a Translate model, we need for some reason to force it to stop acting as a Translate model:
// Detach a behavior from our model:
$this->Category->Behaviors->detach('Translate');
We may also need to find out if our behavior is handling those model callbacks, and if not we then restore its ability to react to them:
// If our behavior is not handling model callbacks
if (!$this->Category->Behaviors->enabled('Translate')) {
// Tell it to start doing so
$this->Category->Behaviors->enable('Translate');
}
Types of behaviors
1) Acl behavior
2) tree behavior
3) containable behavior
4) translate behavior
bootstrap.php in CakePHP
first file that gets loaded when you run a application using cakephp
Elements in CakePHP
Many applications have small blocks of presentation code that need 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
element('helpbox'); ?>
Passing Variables into an Element:
$this->element('helpbox',
array("helptext" => "Oh, this text is very helpful."));
?>
Layouts in CakePHP
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.
layout includes 1)$content_for_layout - contains the view. This is where the view code will be placed.
2)$title_for_layout - contains the page title.
3)$scripts_for_layout - contains any external files and scripts included with the built-in HTML helper. Useful for including javascript and CSS files from views.
Scaffolding in CakePHP
Creating the Table Schemas
CREATE TABLE players (
id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(50) NOT NULL,
position VARCHAR(25) NOT NULL,
team_name VARCHAR(50) NOT NULL
)
Defining the Models and Controller
For scaffolding purposes, creating the controller is amazingly easy; just define the variable $scaffold:
class PlayersController extends AppController
{
var $scaffold;
}
?>
Next let's define the Player model. This is a tad more involved than the controller, but not by much. Place the following code in a file named player.php and save it to the /app/models/ directory.
class Player extends AppModel
{
var $name = 'Player';
var $validate = array(
'firstname' => array(
'rule' => array(
'notEmpty'),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for the firstname field'),
'position' => array(
'rule' => array(
'notEmpty'),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for the position field'),
'teamname' => array(
'rule' => array(
'notEmpty'),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for the team field')
);
}
?>
Believe it or not, you now have a table insertion, modification, and deletion framework at your disposal for players table
Next navigate to http://localhost/cake/players/add and add a few players. Notably, you'll see a dropdown listbox has been created, populated by the previously defined teams! After adding a few players, your list view (http://localhost/cake/players/) will look something like this:
bindModel() and unbindModel()
bindModel():
The basic usage for bindModel() is the encapsulation of a normal association array inside an array whose key is named after the type of association
Syntax:
$this->Model->bindModel(
array('associationName' => array(
'associatedModelClassName' => array(
// normal association keys go here...
)
)
)
);
example:
function anotherAction() {
// There is no Leader hasMany Principles in
// the leader.php model file, so a find here,
// only fetches Leaders.
$this->Leader->find('all');
// Let's use bindModel() to add a new association
// to the Leader model:
$this->Leader->bindModel(
array('hasMany' => array(
'Principle' => array(
'className' => 'Principle'
)
)
)
);
// Now that we're associated correctly,
// we can use a single find function to fetch
// Leaders with their associated principles:
$this->Leader->find('all');
}
unbindModel():
to remove that association in a controller action.
Syntax:
$this->Model->unbindModel(
array('associationType' => array('associatedModelClassName'))
);
Example:
function someAction() {
// This fetches Leaders, and their associated Followers
$this->Leader->find('all');
// Let's remove the hasMany...
$this->Leader->unbindModel(
array('hasMany' => array('Follower'))
);
// Now using a find function will return
// Leaders, with no Followers
$this->Leader->find('all');
// NOTE: unbindModel only affects the very next
// find function. An additional find call will use
// the configured association information.
// We've already used find('all') after unbindModel(),
// so this will fetch Leaders with associated
// Followers once again...
$this->Leader->find('all');
}
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 tags.
Send email using phpmailer and cakephp
1) download the class.phpmailer.php file and place it into vendors folder under your project
click here to download the class.phpmailer.php file
2) place the below code into yours controller
App::import('vendor', 'Writer', array('file' =>'class.phpmailer.php'));
class UsersController extends AppController {
var $name = "Users";
function index(){
$mail = new PHPMailer();
$body="maheshonlyforu";
$subject = "test";
$mail->From = 'mahesh@checksuminfosoft.com';
$mail->FromName = 'mahesh';
$mail->Subject = 'PHPMailer Test Subject';
$mail->MsgHTML($body);
$add = "maheshbabu09@gmail.com"; //to address of mail
$mail->AddAddress($add, 'rakesh');
if(!$mail->Send()) {
echo 'Failed to send mail';
} else {
echo 'Mail sent';
}
}
}
2 comments:
Great Post! you have done great job.Thanks for sharing it with us. Well done and keep posting CakePHP Web Application.
It is nice blog Thank you provide important information and I am searching for the same information to save my time Ruby on Rails Online Training
Post a Comment