Saturday, March 29, 2008

Simple Problem for add/edit in cakephp with data base

First You can create the user table in your database :

For example :

CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`login` varchar(20) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)

Second you can create the thtml file in the view folder the path is /view/users/register.thtml











hidden('User/id',array('value' => $data['User']['id'])));?>




User Name input('User/login',array('value' => $data['User']['login']));?>
Pass word input('User/password',array('value' => $data['User']['password'])));?>





Third you can create the users_controller.php

Path is /controllers/users_controller.php

class UsersController extends AppController
{
var $name= 'Users';
var $helpers = array('Html','Javascript');
function register()
{
$this->set('data',NULL);
if(isset($this->data)){
$this->User->save($this->data);
$this->redirect('users/register');
}
}
function edituser($id=NULL)
{
$data = $this->User->findById($id);
$this->set('data',$data);
if(isset($this->data)){
if($this->User->save($this->data))
$this->redirect('users/edituser/'.$id);
}
$this->render('register');
}
}
?>

Finally You can create the model user.php

path is /models/user.php


Class User extends AppModel{
var $name = 'User';
}
?>

Sunday, March 2, 2008

cakePHP : Configuration

Chapter. Configuration

Table of Contents

Database Configuration
Global Configuration
Routes Configuration
Advanced Routing Configuration: Admin Routing and Webservices
(Optional) Custom Inflections Configuration
Database Configuration
Your app/config/database.php file is where your database configuration all takes place. A fresh install doesn't have a database.php, so you'll need to make a copy of database.php.default. Once you've made a copy and renamed it you'll see the following:

Example 4.1. app/config/database.php

var $default = array('driver' => 'mysql',
'connect' => 'mysql_connect',
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'project_name',
'prefix' => '');



Replace the information provided by default with the database connection information for your application.

One note about the prefix key: the string you enter there will be prepended to any SQL call that Cake makes to your database when working with tables. You define it here once so you don't have to specify it in other places. It also allows you to follow Cake's table naming conventions if you're on a host that only gives you a single database. Note: for HABTM join tables, you only add the prefix once: prefix_apples_bananas, not prefix_apples_prefix_bananas.

CakePHP supports the following database drivers:

mysql

postgres

sqlite

pear-drivername (so you might enter pear-mysql, for example)

adodb-drivername

The 'connect' key in the $default connection allows you to specify whether or not the database connection will be treated as persistent or not. Read the comments in the database.php.default file for help on specifying connection types for your database setup.

Your database tables should also follow the following conventions:

Table names used by Cake should consist of English words in plural, like "users", "authors" or "articles". Note that corresponding models have singular names.

Your tables must have a primary key named 'id'.

If you plan to relate tables, use foreign keys that look like: 'article_id'. The table name is singular, followed by an underscore, followed by 'id'.

If you include a 'created' and/or 'modified' column in your table, Cake will automatically populate the field when appropriate.

You'll also notice that there is a $test connection setting included in the database.php file. Fill out this configuration (or add other similarly formatted configurations) and use it in your application by placing something like:

var $useDbConfig = 'test';
Inside one of your models. You can add any number of additional connection settings in this manner.


Global Configuration

CakePHP's global configuration can be found in app/config/core.php. While we really dislike configuration files, it just had to be done. There are a few things you can change here, and the notes on each of these settings can be found within the comments of the core.php file.

DEBUG: Set this to different values to help you debug your application as you build it. Specifying this setting to a non-zero value will force Cake to print out the results of pr( ) and debug( ) function calls, and stop flash messages from forwarding automatically. Setting it to 2 or higher will result in SQL statements being printed at the bottom of the page.

Also when in debug mode (where DEBUG is set to 1 or higher), Cake will render certain generated error pages, i.e. "Missing Controller," "Missing Action," etc. In production mode, however (where DEBUG is set to 0), Cake renders the "Not Found" page, which can be overridden in app/views/errors/error404.thtml.

CAKE_SESSION_COOKIE: Change this value to the name of the cookie you'd like to use for user sessions in your Cake app.

CAKE_SECURITY: Change this value to indicate your preferred level of sessions checking. Cake will timeout sessions, generate new session ids, and delete old session files based on the settings you provide here. The possible values are:

high: sessions time out after 10 minutes of inactivity, and session id's are regenerated on each request

medium: sessions time out after 20 minutes of inactivity

low: sessions time out after 30 minutes of inactivity

CAKE_SESSION_SAVE: Specify how you'd like session data saved. Possible values are:

cake: Session data is saved in tmp/ inside your Cake installation

php: Session data saved as defined in php.ini

database: Session data saved to database connection defined by the 'default' key.


Routes Configuration

"Routing" is a pared-down pure-PHP mod_rewrite-alike that can map URLs to controller/action/params and back. It was added to Cake to make pretty URLs more configurable and to divorce us from the mod_rewrite requirement. Using mod_rewrite, however, will make your address bar look much more tidy.

Routes are individual rules that map matching URLs to specific controllers and actions. Routes are configured in the app/config/routes.php file. They are set-up like this:

Example 4.2. Route Pattern

$Route->connect (
'URL',
array('controller'=>'controllername',
'action'=>'actionname', 'firstparam')
);
?>



Where:

URL is the regular expression Cake URL you wish to map,

controllername is the name of the controller you wish to invoke,

actionname is the name of the controller's action you wish to invoke,

and firstparam is the value of the first parameter of the action you've specified.

Any parameters following firstparam will also be passed as parameters to the controller action.

The following example joins all the urls in /blog to the BlogController. The default action will be BlogController::index().

Example 4.3. Route Example

$Route->connect ('/blog/:action/*', array('controller'=>'Blog', 'action'=>'index'));
?>

A URL like /blog/history/05/june can then be handled like this:

Example 4.4. Route Handling in a Controller

class BlogController extends AppController
{
function history ($year, $month=null)
{
// .. Display appropriate content
}
}
?>



The 'history' from the URL was matched by :action from the Blog's route. URL elements matched by * are passed to the active controller's handling method as parameters, hence the $year and $month. Called with URL /blog/history/05, history() would only be passed one parameter, 05.

The following example is a default CakePHP route used to set up a route for PagesController::display('home'). Home is a view which can be overridden by creating the file /app/views/pages/home.thtml.

Example 4.5. Setting the Default Route

$Route->connect ('/', array('controller'=>'Pages', 'action'=>'display', 'home'));
?>




Advanced Routing Configuration: Admin Routing and Webservices

There are some settings in /app/config/core.php you can take advantage of in order to organize your application and craft URLs that make the most sense to you and your users.

The first of these is admin routing. If your application has a ProductsController as well as a NewsController, you might want to set up some special URLs so users with administrative privileges can access special actions in those controllers. To keep the URLs nice and easy to read, some people prefer /admin/products/add and /admin/news/post to something like /products/adminAdd and /news/adminPost.

To enable this, first, uncomment the CAKE_ADMIN line in your /app/config/core.php file. The default value of CAKE_ADMIN is 'admin', but you can change it to whatever you like. Remember this string, because you'll need to prepend it to your administrative actions in your controller. So, admin actions in this case would be named admin_actionName(). Here's some examples of desired URLs and possible CAKE_ADMIN and controller action settings:

/admin/products/add CAKE_ADMIN = 'admin'
name of action in ProductsController = 'admin_add()'

/superuser/news/post CAKE_ADMIN = 'superuser'
name of action in NewsController = 'superuser_post()'

/admin/posts/delete CAKE_ADMIN = 'admin'
name of action in PostsController = 'admin_delete()'

Using admin routes allows you to keep your logic organized while making the routing very easy to accomplish.

Note
Please note that enabling admin routes or using them does not enable any sort of authentication or security. You'll need implement those yourself.


Similarly, you can enable Cake's webservices routing to make easier there as well. Have a controller action you'd like to expose as a webservice? First, set WEBSERVICES in /app/config/core.php to 'on'. This enables some automatic routing somewhat similar to admin routing, except that a certain set of route prefixes are enabled:

rss

xml

rest

soap

xmlrpc

What this does is allows you to provide an alternate views that will automatically be available at /rss/controllerName/actionName or /soap/controllerName/actionName. This allows you to create a single action that can have two views: one for normal HTML viewiers, and another for webservices users. By doing this, you can easily allow much of the functionality of your application to be available via webservices.

For example, let's say I have some logic in my application that tells users who is on the phone in my office. I already have a HTML view for this data, but I want to offer it in XML so it can be used in a desktop widget or handheld application. First I need to enable Cake's webservice routing:

Example 4.6. /app/config/core.php (partial)

/**
* The define below is used to turn cake built webservices
* on or off. Default setting is off.
*/
define('WEBSERVICES', 'on');


Next, I can structure the logic in my controller just as I normally would:

Example 4.7. messages_controller.php

class PhonesController extends AppController
{
function doWhosOnline()
{
// this action is where we do all the work of seeing who's on the phone...

// If I wanted this action to be available via Cake's xml webservices route,
// I'd need to include a view at /app/views/posts/xml/do_whos_online.thtml.
// Note: the default view used here is at /app/views/layouts/xml/default.thtml.

// If a user requests /phones/doWhosOnline, they will get an HTML version.
// If a user requests /xml/phones/doWhosOnline, they will get the XML version.
}
}
?>

(Optional) Custom Inflections Configuration


Cake's naming conventions can be really nice - you can name your model Box, your controller Boxes, and everything just works out. There are occasions (especially for our non-english speaking friends) where you may run into situations where Cake's inflector (the class that pluralizes, singularizes, camelCases, and under_scores) might not work as you'd like. If Cake won't recognize your Foci or Fish, editing the custom inflections configuration file is where you'll need to go.

Found at /app/config/inflections.php is a list of Cake variables you can use to adjust the pluralization, singularization of classnames in Cake, along with definining terms that shouldn't be inflected at all (like Fish and Deer, for you outdoorsman cakers) along with irregularities.

Follow the notes inside the file to make adjustments, or use the examples in the file by uncommenting them. You may need to know a little regex before diving in.

cakePHP : Installing CakePHP

Chapter 3. Installing CakePHP

Table of Contents

Introduction
Requirements
Server Requirements
Installing CakePHP
Getting the most recent stable version
Unpacking
Setting Up CakePHP
Development Setup
Production Setup
Advanced Setup: Alternative Installation Options
Configuring Apache and mod_rewrite
Make Sure It's Working

Introduction

So now you know everything there is to know about the structure and purpose of all the CakePHP libraries, or you have skipped to this part because you don't care about that stuff and just want to start playing. Either way, you're ready to get your hands dirty.

This chapter will describe what must be installed on the server, different ways to configure your server, downloading and installing CakePHP, bringing up the default CakePHP page, and some troubleshooting tips just in case everything does not go as planned.

Requirements

In order use CakePHP you must first have a server that has all the required libraries and programs to run CakePHP:

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, PostgreSQL and a wrapper for ADODB).

Installing CakePHP

Getting the most recent stable version

There are a few ways you can secure a copy of CakePHP: getting a stable release from CakeForge, grabbing a nightly build, or getting a fresh version of code from SVN.

To download a stable version of code, check out the files section of the CakePHP project at CakeForge by going to http://cakeforge.org/projects/cakephp/.

To grab a nightly, download one from http://cakephp.org/downloads/index/nightly. These nightly releases are stable, and often include the bug fixes between stable releases.

To grab a fresh copy from our SVN repository, use your favorite SVN client and connect to https://svn.cakephp.org/repo/trunk/cake/ and choose the version you're after.

Unpacking

Now that you've downloaded the most recent release, place that compressed package on your web server in the webroot. Now you need to unpack the CakePHP package. There are two ways to do this, using a development setup, which allows you to easily view many CakePHP applications under a single domain, or using the production setup, which allows for a single CakePHP application on the domain.

Configuring Apache and mod_rewrite


While CakePHP is built to work with mod_rewrite out of the box, we've noticed that a few users struggle with getting everything to play nicely on their systems. Here are a few things you might try to get it running correctly:

Make sure that an .htaccess override is allowed: in your httpd.conf, you should have a section that defines a section for each Directory on your server. Make sure the AllowOverride is set to All for the correct Directory.

Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.

For some reason or another, you might have obtained a copy of CakePHP without the needed .htaccess files. This sometimes happens because some operating systems treat files that start with '.' as hidden, and don't copy them. Make sure your copy of CakePHP is from the downloads section of the site or our SVN repository.

Make sure you are loading up mod_rewrite correctly! You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so and AddModule mod_rewrite.c in your httpd.conf.

If you are installing Cake into a user directory (http://example.com/~myusername/), you'll need to modify the .htaccess file in the base directory of your Cake installation. Just add the line "RewriteBase /~myusername/".

If for some reason your URLS are suffixed with a long, annoying session ID (http://example.com/posts/?CAKEPHP=4kgj577sgabvnmhjgkdiuy1956if6ska), you might also add "php_flag session.trans_id off" to the .htaccess file at the root of your installation as well.

Make Sure It's Working

Alright, lets see this baby in action. Depending on which setup you used, you should point your browser to http://www.example.com or http://www.example.com/cake. At this point, you'll be presented with CakePHP's default home, and a message that tells you the status of your current database connection.

Congratulations! You are ready to create your first Cake-based application.

cakePHP:Basic Concepts

Chapter 2. Basic Concepts

Table of Contents

Introduction

The MVC Pattern
Overview of the Cake File Layout

Introduction
This chapter is a short, casual introduction to MVC concepts as they are implemented in Cake. If you're new to MVC (Model View Controller) patterns, this chapter is definitely for you. We begin with a discussion of general MVC concepts, work our way into the specific application of MVC in CakePHP, and show some simple examples of CakePHP using the MVC pattern.


The MVC Pattern

Model-View-Controller is a software design pattern that helps you logically separate your code, make it more reusable, maintainable, and generally better. Model View Controller was first described by the author group Gang of Four. Dean Helman wrote (an extract from Objective Toolkit Pro white paper):


"The MVC paradigm is a way of breaking an application, or even just a piece of an application's interface, into three parts: the model, the view, and the controller. MVC was originally developed to map the traditional input, processing, output roles into the GUI realm.

Input -> Processing -> Output

Controller -> Model -> View

"The user input, the modeling of the external world, and the visual feedback to the user are separated and handled by model, view port and controller objects. The controller interprets mouse and keyboard inputs from the user and maps these user actions into commands that are sent to the model and/or view port to effect the appropriate change. The model manages one or more data elements, responds to queries about its state, and responds to instructions to change state. The view port manages a rectangular area of the display and is responsible for presenting data to the user through a combination of graphics and text."


In Cake terms, the Model represents a particular database table/record, and it's relationships to other tables and records. Models also contain data validation rules, which are applied when model data is inserted or updated. The View represents Cake's view files, which are regular HTML files embedded with PHP code. Cake's Controller handles requests from the server. It takes user input (URL and POST data), applies business logic, uses Models to read and write data to and from databases and other sources, and lastly, sends output data to the appropriate view file.

To make it as easy as possible to organize your application, Cake uses this pattern not only to manage how objects interact within your application, but also how files are stored, which is detailed next.


Overview of the Cake File Layout

When you unpack Cake on your server you will find three main folders -

app
cake
vendors


The cake folder is where the core libraries for Cake lay and you generally won't ever need to touch it.

The app folder is where your application specific folders and files will go. The separation between the cake folder and the app folder make it possible for you to have many app folders sharing a single set of Cake libraries. This also makes it easy to update CakePHP: you just download the latest version of Cake and overwrite your current core libraries. No need to worry about overwriting something you wrote for your app.

You can use the vendors directory to keep third-party libraries in. You will learn more about vendors later, but the basic idea is that you can access classes you've placed in the vendors directory using Cake's vendor() function.

Let's look at the entire file layout:

/app
/config - Contains config files for your database, ACL, etc.

/controllers - Controllers go here
/components - Components go here

/index.php - Allows you to deploy cake with /app as the DocumentRoot

/models - Models go here

/plugins - Plugins go here

/tmp - Used for caches and logs

/vendors - Contains third-party libaries for this application

/views - Views go here
/elements - Elements, little bits of views, go here
/errors - Your custom error pages go here
/helpers - Helpers go here
/layouts - Application layout files go here
/pages - Static views go here

/webroot - The DocumentRoot for the application
/css
/files
/img
/js

/cake - Cake's core libraries. Don't edit any files here.

index.php

/vendors - Used for server-wide third-party libraries.

VERSION.txt - Let's you know what version of Cake you're using.

Introduction to CakePHP

Chapter 1. Introduction to CakePHP

Table of Contents

What is CakePHP?
Why CakePHP?
History of CakePHP
What is CakePHP?


CakePHP is a free open-source rapid development framework for PHP. Its a structure of libraries, classes and run-time infrastructure for programmers creating web applications originally inspired by the Ruby on Rails framework. Our primary goal is to enable you to work in a structured and rapid manner - without loss of flexibility.

Why CakePHP?

CakePHP has several features that make it a great choice as a framework for developing applications swiftly and with the least amount of hassle. Here are a few in no particular order:

Active, friendly community

Flexible Licensing

Compatibility with PHP4 and PHP5

Integrated CRUD for database interaction and simplified queries

Application Scaffolding

Model View Controller (MVC) Architecture

Request dispatcher with good looking, custom URLs

Built-in Validation

Fast and flexible templating (PHP syntax, with helpers)

View Helpers for AJAX, Javascript, HTML Forms and more

Security, Session, and Request Handling Components

Flexible access control lists

Data Sanitization

Flexible View Caching

Works from any web site subdirectory, with little to no Apache configuration involved


History of CakePHP


In 2005, Michal Tatarynowicz wrote a minimal version of a Rapid Application Framework in PHP. He found that it was the start of a very good framework. Michal published the framework under the MIT license, dubbing it Cake, and opened it up to a community of developers, who now maintain Cake under the name CakePHP.