March 11, 2015

Home » » » Build CRUD App Demo in Zend Framework 2 - Create Read Update Show and Delete Album in Zend 2

Build CRUD App Demo in Zend Framework 2 - Create Read Update Show and Delete Album in Zend 2

Posted by Unknown
0

Install PHP, MySQL, Apache2

$ sudo apt-get update
$ sudo apt-get apache2
$ sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt
$ sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql
$ curl -s https://getcomposer.org/installer | php --
May be, install curl if dont have on your systems.

Clone ZendSkeletonApplication and install

$ cd
$ mkdir Workspace
$ cd Workspace
$ git clone git://github.com/zendframework/ZendSkeletonApplication.git
$ cd ZendSkeletonApplication
$ php composer.phar self-update
$ php composer.phar install

Web server setup (use PHP CLI for development env)

$ cd ZendSkeletonApplication
$ php -s 0.0.0.0:8080 -t public/ public/index.php

Then, open web browser and point to : http://localhost:8080

Create new module (Album module)

Create the directory structure for the album is as follows:

<?php
 
namespace Album;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
             //   __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }
}

Create ZendSkeletonApplication/module/Album/config/module.config.php

<?php
return array(
    'controllers' => array(
        'invokables' => array(
            'Album\Controller\Album' => 'Album\Controller\AlbumController',
        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'album' => __DIR__ . '/../view',
        ),
    ),
);

Tell ZendSkeletonApplication that use modules Album Open ZendSkeletonApplication / config / application.config.php and add the line:

<?php
return array(
    'modules' => array(
        'Application',
        'Album',                  // <-- data-blogger-escaped-add="" data-blogger-escaped-line="" data-blogger-escaped-module_listener_options="" data-blogger-escaped-this=""> array(
        'config_glob_paths'    => array(
            'config/autoload/{,*.}{global,local}.php',
        ),
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);

Create routes for controller and script views

Add following line to module.config.php

# ZendSkeletonApplication/module/Album/config/module.config.php

     // The following section is new and should be added to your file
     'router' => array(
         'routes' => array(
             'album' => array(
                 'type'    => 'segment',
                 'options' => array(
                     'route'    => '/album[/:action][/:id]',
                     'constraints' => array(
                         'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                         'id'     => '[0-9]+',
                     ),
                     'defaults' => array(
                         'controller' => 'Album\Controller\Album',
                         'action'     => 'index',
                     ),
                 ),
             ),
         ),
     ),

The code above will take on the module Album app with the default index.php page

Create controller

Create AlbumController.php in module/Album/src/Album/Controller/

<?php
 
namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AlbumController extends AbstractActionController
{
    public function indexAction()
    {
    }

    public function addAction()
    {
    }

    public function editAction()
    {
    }

    public function deleteAction()
    {
    }
}

Create views script for AlbumController

module/Album/view/album/album/index.phtml 
module/Album/view/album/album/add.phtml 
module/Album/view/album/album/edit.phtml 
module/Album/view/album/album/delete.phtml 

Test module setup

http://localhost:8080/album  => index page
http://localhost:8080/album/add  => add album page
http://localhost:8080/album/edit  => edit album page
http://localhost:8080/album/delete  => delete album page

Screenshots

Database setup

Create database (demo: zf2tutorial)

$ mysql -u root -p
mysql > create database zf2tutorial;
mysql > use zf2tutorial;
 CREATE TABLE album (
   id int(11) NOT NULL auto_increment,
   artist varchar(100) NOT NULL,
   title varchar(100) NOT NULL,
   PRIMARY KEY (id)
 );
 INSERT INTO album (artist, title)
     VALUES  ('The  Military  Wives',  'In  My  Dreams');
 INSERT INTO album (artist, title)
     VALUES  ('Adele',  '21');
 INSERT INTO album (artist, title)
     VALUES  ('Bruce  Springsteen',  'Wrecking Ball (Deluxe)');
 INSERT INTO album (artist, title)
     VALUES  ('Lana  Del  Rey',  'Born  To  Die');
 INSERT INTO album (artist, title)
     VALUES  ('Gotye',  'Making  Mirrors');

Create model files

Create model files in module/Album/src/Album/Model/

Create Album.php
<?php

namespace Album\Model;

 class Album
 {
     public $id;
     public $artist;
     public $title;

     public function exchangeArray($data)
     {
         $this->id     = (!empty($data['id'])) ? $data['id'] : null;
         $this->artist = (!empty($data['artist'])) ? $data['artist'] : null;
         $this->title  = (!empty($data['title'])) ? $data['title'] : null;
     }
 }

Create AlbumTable.php

<?php
namespace Album\Model;

use Zend\Db\TableGateway\TableGateway;

class AlbumTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function getAlbum($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveAlbum(Album $album)
    {
        $data = array(
            'artist' => $album->artist,
            'title'  => $album->title,
        );

        $id = (int) $album->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getAlbum($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Album id does not exist');
            }
        }
    }

    public function deleteAlbum($id)
    {
        $this->tableGateway->delete(array('id' => (int) $id));
    }
}

Using ServiceManager to configure the table gateway and inject into album table

<?php
namespace Album;

// Add these import statements:
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

class Module
{
    // getAutoloaderConfig() and getConfig() methods here

    // Add this method:
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Album\Model\AlbumTable' =>  function($sm) {
                    $tableGateway = $sm->get('AlbumTableGateway');
                    $table = new AlbumTable($tableGateway);
                    return $table;
                },
                'AlbumTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Album());
                    return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
                },
            ),
        );
    }
}

Config for connect to database

Open ZendSkeletonApplication/config/autoload/global.php and edit:
 return array(
     'db' => array(
         'driver'         => 'Pdo',
         'dsn'            => 'mysql:dbname=zf2tutorial;host=localhost',
         'driver_options' => array(
             PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
         ),
     ),
     'service_manager' => array(
         'factories' => array(
             'Zend\Db\Adapter\Adapter'
                     => 'Zend\Db\Adapter\AdapterServiceFactory',
         ),
     ),
 );

Then, Create ZendSkeletonApplication/config/autoload/local.php and add:

<?php

return array(
    'db' => array(
        'username' => 'YOUR USERNAME HERE',
        'password' => 'YOUR PASSWORD HERE',
    ),
);

Open AlbumController.php and add getAlbumTable() function

 // module/Album/src/Album/Controller/AlbumController.php:
     public function getAlbumTable()
     {
         if (!$this->albumTable) {
             $sm = $this->getServiceLocator();
             $this->albumTable = $sm->get('Album\Model\AlbumTable');
         }
         return $this->albumTable;
     }

Edit indexAction() in AlbumController.php for listing all albums in database

 // module/Album/src/Album/Controller/AlbumController.php:
 // ...
     public function indexAction()
     {
         return new ViewModel(array(
             'albums' => $this->getAlbumTable()->fetchAll(),
         ));
     }
 // ...

Finally, show ra all album: index.phtml in view

<?php

 // module/Album/view/album/album/index.phtml:

 $title = 'My albums';
 $this->headTitle($title);
 ?>
 <h1><?php echo $this->escapeHtml($title); ?></h1>
 <p>
     <a href="<?php echo $this->url('album', array('action'=>'add'));?>">Add new album</a>
 </p>

 <table class="table">
 <tr>
     <th>Title</th>
     <th>Artist</th>
     <th>&nbsp;</th>
 </tr>
 <?php foreach ($albums as $album) : ?>
 <tr>
     <td><?php echo $this->escapeHtml($album->title);?></td>
     <td><?php echo $this->escapeHtml($album->artist);?></td>
     <td>
         <a href="<?php echo $this->url('album',
             array('action'=>'edit', 'id' => $album->id));?>">Edit</a>
         <a href="<?php echo $this->url('album',
             array('action'=>'delete', 'id' => $album->id));?>">Delete</a>
     </td>
 </tr>
 <?php endforeach; ?>
 </table>

Screenshots

CRUD for Album module

Show an album

Add viewAction($id) to AlbumController.php
<?php

// Some code , ex: namespace . .. 
class AlbumController extends AbstractActionController
{
 //  ...
 protected $id;
 // …
     public function viewAction($id)
     {
        $id = (int) $this->params()->fromRoute('id', 0);
        return array(
          'id'    => $id,
          'album' => $this->getAlbumTable()->getAlbum($id)
        );
     }
} 

Create module/Album/view/album/album/view.phtml

Then, access to: http://localhost:8080/album/view/1

Create new album

Create a file called AlbumForm.php in module/Album/src/Album/Form:
<?php

namespace Album\Form;

 use Zend\Form\Form;

 class AlbumForm extends Form
 {
     public function __construct($name = null)
     {
         // we want to ignore the name passed
         parent::__construct('album');

         $this->add(array(
             'name' => 'id',
             'type' => 'Hidden',
         ));
         $this->add(array(
             'name' => 'title',
             'type' => 'Text',
             'options' => array(
                 'label' => 'Title',
             ),
         ));
         $this->add(array(
             'name' => 'artist',
             'type' => 'Text',
             'options' => array(
                 'label' => 'Artist',
             ),
         ));
         $this->add(array(
             'name' => 'submit',
             'type' => 'Submit',
             'attributes' => array(
                 'value' => 'Go',
                 'id' => 'submitbutton',
             ),
         ));
     }
 }
Open Album.php file in module/Album/src/Album/Model:
<?php

namespace Album\Model;

 // Add these import statements
 use Zend\InputFilter\InputFilter;
 use Zend\InputFilter\InputFilterAwareInterface;
 use Zend\InputFilter\InputFilterInterface;

 class Album implements InputFilterAwareInterface
 {
     public $id;
     public $artist;
     public $title;
     protected $inputFilter;                       // <-- data-blogger-escaped-add="" data-blogger-escaped-data="" data-blogger-escaped-exchangearray="" data-blogger-escaped-function="" data-blogger-escaped-public="" data-blogger-escaped-this-="" data-blogger-escaped-this="" data-blogger-escaped-variable="">id     = (isset($data['id']))     ? $data['id']     : null;
         $this->artist = (isset($data['artist'])) ? $data['artist'] : null;
         $this->title  = (isset($data['title']))  ? $data['title']  : null;
     }

     // Add content to these methods:
     public function setInputFilter(InputFilterInterface $inputFilter)
     {
         throw new \Exception("Not used");
     }

     public function getInputFilter()
     {
         if (!$this->inputFilter) {
             $inputFilter = new InputFilter();

             $inputFilter->add(array(
                 'name'     => 'id',
                 'required' => true,
                 'filters'  => array(
                     array('name' => 'Int'),
                 ),
             ));

             $inputFilter->add(array(
                 'name'     => 'artist',
                 'required' => true,
                 'filters'  => array(
                     array('name' => 'StripTags'),
                     array('name' => 'StringTrim'),
                 ),
                 'validators' => array(
                     array(
                         'name'    => 'StringLength',
                         'options' => array(
                             'encoding' => 'UTF-8',
                             'min'      => 1,
                             'max'      => 100,
                         ),
                     ),
                 ),
             ));

             $inputFilter->add(array(
                 'name'     => 'title',
                 'required' => true,
                 'filters'  => array(
                     array('name' => 'StripTags'),
                     array('name' => 'StringTrim'),
                 ),
                 'validators' => array(
                     array(
                         'name'    => 'StringLength',
                         'options' => array(
                             'encoding' => 'UTF-8',
                             'min'      => 1,
                             'max'      => 100,
                         ),
                     ),
                 ),
             ));

             $this->inputFilter = $inputFilter;
         }

         return $this->inputFilter;
     }
 }
Open AlbumController.php and add:
 // module/Album/src/Album/Controller/AlbumController.php:

 //...
 use Zend\Mvc\Controller\AbstractActionController;
 use Zend\View\Model\ViewModel;
 use Album\Model\Album;          // <-- data-blogger-escaped-add="" data-blogger-escaped-addaction="" data-blogger-escaped-album="" data-blogger-escaped-albumform="" data-blogger-escaped-content="" data-blogger-escaped-form-="" data-blogger-escaped-form="new" data-blogger-escaped-function="" data-blogger-escaped-import="" data-blogger-escaped-lbumform="" data-blogger-escaped-method:="" data-blogger-escaped-orm="" data-blogger-escaped-public="" data-blogger-escaped-this="" data-blogger-escaped-to="" data-blogger-escaped-use="">get('submit')->setValue('Add');

         $request = $this->getRequest();
         if ($request->isPost()) {
             $album = new Album();
             $form->setInputFilter($album->getInputFilter());
             $form->setData($request->getPost());

             if ($form->isValid()) {
                 $album->exchangeArray($form->getData());
                 $this->getAlbumTable()->saveAlbum($album);

                 // Redirect to list of albums
                 return $this->redirect()->toRoute('album');
             }
         }
         return array('form' => $form);
     }
Open add.phtml view script and edit:
 <?php
 // module/Album/view/album/album/add.phtml:

 $title = 'Add new album';
 $this->headTitle($title);
 ?>
 <h1><?php echo $this->escapeHtml($title); ?></h1>
 <?php
 $form->setAttribute('action', $this->url('album', array('action' => 'add')));
 $form->prepare();

 echo $this->form()->openTag($form);
 echo $this->formHidden($form->get('id'));
 echo $this->formRow($form->get('title'));
 echo $this->formRow($form->get('artist'));
 echo $this->formSubmit($form->get('submit'));
 echo $this->form()->closeTag();

More method edit, delete chi tiết xem tại : http://framework.zend.com

Screenshots






0 comments:

Post a Comment

Popular Posts

Labels

Archive

 

Blogroll

Recepies

Flickr Images

Copyright © 2014. Tutorials Blog - All Rights Reserved