Simple Application in CakePhp

Toady I have done my first simple application  in CakePHP .

My App name is Blog .

Now I am going to tech you how to make simple app in CakePHP.

First create controller.

PostsController.php

<?php
class PostsController extends AppController{
public $helper = array('Html','Form');
public $componets = array('Session');
public function index(){
$this->set('posts',$this->Post->find('all'));
}
public function view($id = null){

if(!$id){
throw new NotFoundException(__('Invalid Post'));
}
$post = $this->Post->findByid($id);
if(!$post){
throw new NotFoundException(__('Invalid Post'));
}
$this->set('post',$post);
}
public function add(){
if($this->request->is('post')){
$this->Post->create();
if($this->Post->save($this->request->data)){
$this->Session->setFlash(__('Post is saved'));
return $this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('not save'));
}
}
}
?>

 

Now create your Model

Post.php

 

<?php
class Post extends AppModel{
public $validate = array(
'title'=>array(
'rule'=>'notEmpty'
),
'body'=>array(
'rule'=>'notEmpty'
),
);
}
?>

Now make your views for different actions

 

index.ctp              //homepage

 

<h1>Blog Posts</h1>
<?php
echo $this->Html->link('Add Post',array('controller'=>'posts','action'=>'add'));
?>
<table>
<tr>
<th>Td</th>
<th>Title</th>
<th>Created</th>
</tr>
<?php
foreach($posts as $post):
?>
<tr>
<td><?php echo $post['Post']['id'];?></td>
<td>
<?php
echo $this->Html->link($post['Post']['title'],array('controller'=>'posts','action'=>'view',$post['Post']['id']));?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
<?php unset($post); ?>
</table>

 

 

add.ctp       //For add the data

<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows'=>'3'));
echo $this->Form->end('Save Post');
?>

 

view.php                //for Show the data

 

<h1><?php echo h($post['Post']['title']);?></h1>
<p><small>Created:<?php echo $post['Post']['created'];?></small></p>
<p><?php echo h($post['Post']['body']);?></p>

 

 

 

 

 

Now make some settings in route.php file in cakephp

 

Router::connect("/posts/", array('controller' => 'Posts', 'action' => 'index'));

 

 

now run your application on browser and check your application work.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s