Wednesday 19 June 2013

Example code - CakePHP

CAKEPHP FOLDER 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

CakePHP’s app folder is where you will do most of your application development. Let’s look a little closer at the folders inside of app.
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.


REQUIREMENTS

 HTTP Server. For example: Apache. 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
  • Microsoft SQL Server
  • Oracle
  • SQLite

CORE COMPONENTS

CakePHP has a number of built-in components. They provide out of the box functionality for several commonly used tasks.
The Acl component provides an easy to use interface for database and ini based access control lists.
The auth component provides an easy to use authentication system using a variety of authentication processes, such as controller callbacks, Acl, or Object callbacks.
The cookie component behaves in a similar fashion to the SessionComponent in that it provides a wrapper for PHP's native cookie support.
An interface that can be used to send emails using one of several mail transfer agents including php's mail() and smtp.
The request handler allows you to introspect further into the requests of your visitors and inform your application about the content types and requested information.
The security component allows you to set tighter security and use and manage HTTP authentication.
The session component provides a storage independent wrapper to PHP's sessions.
To learn more about each component see the menu on the left, or learn more about creating your own components.
All core components now can be configured in the $components array of a controller.

Step1:   Under the appà configàcore.php file set according to the


A random string used in security hashing methods.
 *///praveen.. url get from https://www.grc.com/passwords.htm----------------------------------------------------->
            Configure::write('Security.salt', 'LwjZfapqsfxkDpCBstGObx6fGnOU5BrQ9ghxjOuRkdYUtpo1MOIcN5JXZo7FLhB');

/**
 * A random numeric string (digits only) used to encrypt/decrypt strings.
 */
            Configure::write('Security.cipherSeed', '123456789');

/**
 * Apply timestamps with the last modified time to static assets (js, css, images).
 * Will append a querystring parameter containing the time the file was modified. This is
 * useful for invalidating browser caches.

Step2:   Under the appà configàdatabase.php  file set the data according to your already created base

class DATABASE_CONFIG {

            public $default = array(
                   'datasource' => 'Database/Mysql',
                   'persistent' => false,
                   'host' => 'localhost',
                   'login' => 'root',
                   'password' => '',
                   'database' => 'cackeDB1',
                   'prefix' => '',
                   //'encoding' => 'utf8',
          );

            public $test = array(
                        'datasource' => 'Database/Mysql',
                        'persistent' => false,
                        'host' => 'localhost',
                        'login' => 'user',
                        'password' => 'password',
                        'database' => 'test_database_name',
                        'prefix' => '',
                        //'encoding' => 'utf8',
            );
}
Step 3:
1)Under the Model folder  you should create tudent.php file


<?php
Class tudent extends AppModel
{
var $name='tudent';
// tudents is table name but here used only tudent singular word of table
public  $validate=array
(
'name'=>array(
'name_must_not_be_blanck'=>array('rules'=>'not empty','message'=>' begins with capital letter'),
'name_must_be_unique'=>array('rule'=>'must unique',
'message'=>'this name already existst'
)
),
'address'=>array(
'body_must_not_be_blank'=>array(
'rules'=>'not empty',
'message'=>' begins with capital letter'
)
)
);
/*
public $validate=array
('name'=>array(
'rule'=>'notEmpty'),
'address'=>array(
'rule'=>'notEmpty'),
'mark'=>array(
'rule'=>'notEmpty')
);*/
}
/*class Employee extends AppModel
{
public $name='employee';*/
?>

Step 4:
2) you shoul create under the controller folder…tudentsController.php file


<?php

Class tudentsController extends AppController{
 var $name='tudents';


public function index()
{
$this->set('a',$this->tudent->find('all'));
}


public function hello()
{

}


//--------------
public function add()
 {
        if($this->request->is('post'))
 {
    if($this->tudent->save($this->request->data))
    {
      $this->Session->setFlash('Your post has been saved');
       $this->redirect(array('action'=>'index'));
     }}
 else
    {
    $this->Session->setFlash('Unable to add your post');
    }
 }


public function edit($id=null)
{$this->tudent->id=$id;
if($this->request->is('get'))
    {
    $this->request->data=$this->tudent->read();
     }
else 
      {if($this->tudent->save($this->request->data))
                
                              {$this->Session->setFlash('your post has been updated');
                                      $this->redirect(array('action'=>'index'));
                              }
else
          {$this->Session->setFlash('Unable to update your post');
          }                                     
       }  
             
}



public function del($id=NULL)
{
$this->tudent->delete($id);
$this->Session->setFlash('The post with id :'.$id.'has been deleted.');
 $this->redirect(array('action'=>index));

/*if($this->request->is('get'))
  {
  throw new MethodNotAllowedException();
 
   }
   if($this->tudent->delete($id))
   {$this->Session->setFlash('The post with id :'.$id.'has been deleted.');
   $this->redirect(array('action'=>index));
   }*/
}
//---------------

 public function           find()
{
$this->set('a',$this->Employee->find('all'));
}
           



}
?>
Step 5:
3) under the view you should create all controller files


3.1) first create index.ctp file




<p><h1>hai praveen </h1>
<br>
<p>
<marquee >welcome to php </marquee>
<table>
<tr>
<!--<th>id</th>--!>
<th> name</th>
<th>address</th>
<th>Mark</th>
<th> Your Action</th>
</tr>

<?php foreach($a as $b) {?>
<tr>

<!--<td>
<?php// echo  $b['tudent'] ['id'] ;?>
</td>--!>

<td>
<?php echo $b['tudent'] ['name']; ?>
</td>

<td>
<?php echo $b['tudent'] ['address']; ?>
</td>

<td>
<?php echo $b['tudent'] ['mark']; ?>
</td>

<td>
<?php echo $this->Html->link( 'Edit' ,array('controller'=>'tudents','action'=>'edit',$b['tudent']['id'])); ?>
</td>

<td>
<?php echo $this->Html->link( 'Delete' ,array('controller'=>'tudents','action'=>'del',$b['tudent']['id']),NULL,'Are you shure you want to delete the data'); ?>
</td>
</tr>
<?php
}
?>
<tr>
<td>
<?php echo $this->Html->link($b['tudent'] ['name'],array('controller'=>'tudents','action'=>'hello',$b['tudent']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link('ADD DATA',array('controller'=>'tudents','action'=>'add',$b['tudent']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link('EDIT DATA',array('controller'=>'tudents','action'=>'edit',$b['tudent']['id'])); ?>
</td>

</tr>
</table>

3.2)second you should create  hello.ctp file

<h3> hello world</h3>
<p>welcome to MVC praveen............</p>

<?php echo $this->Html->link('back',array('controller'=>'tudents','action'=>'index')); ?>

3.3) you should create third ctp file named as add.ctp
<tr>
<td>
<h1>Add employ </h1>
</td>
</tr>
<?php
echo $this->Form->create('tudent',array('action'=>'add'));
echo $this->Form->input('name');
echo $this->Form->input('address',array('rows'=>'1'));
echo $this->Form->input('mark');
echo $this->Form->end('Save Employee');
?>
<br>
<?php echo $this->Html->link('back',array('controller'=>'tudents','action'=>'index')); ?>

3.4) edit.ctp



<h1>Edit post</h1>
<?php
 echo $this->Form->create('tudent',array('action'=>'edit'));
 echo $this->Form->input('name');
 echo $this->Form->input('address');
 echo $this->Form->input('mark');
 echo $this->Form->input('id',array('type'=>'hidden'));
 echo $this->Form->end('Save post');
 ?>

3.5)del.ctp

<?php
 echo $this->Form->create('tudent',array('action'=>'del'));
 echo $this->Form->input('name');
 echo $this->Form->input('address');
 echo $this->Form->input('mark');
 echo $this->Form->input('id',array('type'=>'hidden'));
 echo $this->Form->end('Save post');
 ?>

3.6) find.ctp

<?php
 echo $this->Form->create('tudent',array('action'=>'find'));
 echo $this->Form->input('name');
 echo $this->Form->input('address');
 echo $this->Form->input('mark');
 echo $this->Form->input('id',array('type'=>'hidden'));
 echo $this->Form->end('Save post');
 ?>

Step 6: RUN
Browse url: http://localhost:81/cackephp1/tudents/
http://localhost:81/cackephp1/tudents/hello

1 comment:

Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using reso...