zend framework 2 database example

Oct 13, 2012   //   by kdecom   //   database, zend framewok 2, zend framework tutorial, zf2  //  No Comments
Zend frame work 2 and Database Interaction
Zend Framework 2 and Database Interaction

Well i hope some of you like the latest release of Zend framework 2 Hello world blog.

Now for any application or website its necessary to have a database interaction to save the user input and etc etc.

So in this part i will get the list of the games from the Database table.

First thing that i am going to do is create a folder structure like this.

Now Next problem is how does zend framework 2 knows how to load a game module.

To do that Zend framework has the module manager. All we need to do is just let them know we have a new module called game.

So create new file inside your game module called Module.php and autoload_classmap.php

So your new folder structure looks like this..

Now open a module/Game/Module.php and paste this code…

 —>
namespace Game;

class Module {

public function getAutoloaderConfig() {
return array(
‘ZendLoaderClassMapAutoloader’ => array(
__DIR__ . ‘/autoload_classmap.php’,
),
‘ZendLoaderStandardAutoloader’ => array(
‘namespaces’ => array(
__NAMESPACE__ => __DIR__ . ‘/src/’ . __NAMESPACE__,
),
),
);
}
public function getConfig() {
return include __DIR__ . ‘/config/module.config.php’;
}
}

 

and next open a file called /module/game/autoload_classmap.php and paste a code

 —>

return array();

ENDS —>

Now next step is Open a file called:-

APPLICATION_PATH/config/application.config.php

And add a line for new module so finally your file will looks like this:-

 —>


return array(
‘modules’ => array(
‘Application’,
‘Game’
),
‘module_listener_options’ => array(
‘config_glob_paths’    => array(
‘config/autoload/{,*.}{global,local}.php’,
),
‘module_paths’ => array(
‘./module’,
‘./vendor’,
),
),
);

ENDS —>

Next config File that you need to setup is the module config file

APPLICATION_PATH/module/Game/config/module.config.php

STARTS—>

return array(
‘controllers’ => array(
‘invokables’ => array(
‘GameControllerIndex’ => ‘GameControllerGameController’,
),
),
‘router’ => array(
‘routes’ => array(
‘game’ => array(
‘type’ => ‘segment’,
‘options’ => array(
‘route’ => ‘/game[/:action][/:id]’,
‘constraints’ => array(
‘action’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
‘id’ => ‘[0-9]+’,
),
‘defaults’ => array(
‘controller’ => ‘GameControllerIndex’,
‘action’ => ‘index’,
),
),
),
),
),
‘view_manager’ => array(
‘template_path_stack’ => array(
‘game’ => __DIR__ . ‘/../view’,
),
),
);

ENDS —>

This one need little bit of more explaination

First of all 


‘invokables’ => array(
‘GameControllerIndex’ => ‘GameControllerGameController’,
),

For this array key => “GAMEControllerIndex”
And          Values => “GameControllerGameController”

Key has to be unique for all of your modules…
Value is a path for your controller ..

MODULE/CONTROLLER/CONTROLLER_NAME_FILE_NAME

Next array is your route array and in Zend Framework 2 you can chanage the default ACTION as well which was not able to do it in old Zend framework.

So we are about to finished things up soon.. So yes don’t get bored.. So finally all setup part is done and now we going to add a controller and views and actual coding…

Now add a file called GameController.php inside a controller folder

APPLICATION_PATH/module/Game/src/Game/Controller/GameController.php



STARTS —>
namespace GameController;

use ZendMvcControllerAbstractActionController;
use ZendViewModelViewModel;

class GameController extends AbstractActionController {

public function indexAction() {

return new ViewModel(array(
‘title’ => ‘Game Module’,
));
}

}


ENDS —>

For now i am just displaying a Game Module on frontend side…just to make sure our setup is correct.

Next add a view file inside a view folder…

APPLICATION_PATH/module/Game/view/game/game/index.phtml

STARTS—>



 



ENDS —>

Now execute url

www.example.com/public/game

You should be able to see a 

GAME MODULE

If it is not working i would suggess add a comment what error you got and we try to solve it…


Now next thing we gona do is:-
Setup a database and fetch all the Data…


APPLICATION_PATH/config/autoload/global.php

—>
// Changed the highlighted line with your database name..
return array(
‘db’ => array(
‘driver’         => ‘Pdo’,
‘dsn’            => ‘mysql:dbname=kd_tutorial;host=localhost’,
‘driver_options’ => array(
PDO::MYSQL_ATTR_INIT_COMMAND => ‘SET NAMES ‘UTF8”
),
),
‘service_manager’ => array(
‘factories’ => array(
‘ZendDbAdapterAdapter’
=> ‘ZendDbAdapterAdapterServiceFactory’,
),
),
);

ENDS —>

APPLICATION_PATH/config/autoload/local.php

—>

return array(
‘db’ => array(
‘username’ => ‘YOUR_DB_USERNAME’,
‘password’ => ‘YOUR_DB_PASSWORD’,
),
);


ENDS —>

 Now you have to create two model talbe files…

APPLICATION_PATH/module/Game/src/Game/Model/Game.php

—>

namespace GameModel;

class Game
{
public $id;
public $type;
public $title;

public function exchangeArray($data)
{
$this->id     = (isset($data[‘id’])) ? $data[‘id’] : null;
$this->type   = (isset($data[‘type’])) ? $data[‘type’] : null;
$this->title  = (isset($data[‘title’])) ? $data[‘title’] : null;
}
}

ENDS —>

APPLICATION_PATH/module/Game/src/Game/Model/GameTable.php
  
—> 

 namespace GameModel;

use ZendDbAdapterAdapter;
use ZendDbResultSetResultSet;
use ZendDbTableGatewayAbstractTableGateway;

class GameTable extends AbstractTableGateway
{
protected $table = ‘game’;

public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;

$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new Game());

$this->initialize();
}

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

public function getGame($id)
{
$id  = (int) $id;

$rowset = $this->select(array(
‘id’ => $id,
));

$row = $rowset->current();

if (!$row) {
throw new Exception(“Could not find row $id”);
}

return $row;
}

public function saveGame(Game $game)
{
$data = array(
‘type’ => $game->type,
‘title’  => $game->title,
);

$id = (int) $game->id;

if ($id == 0) {
$this->insert($data);
} elseif ($this->getGame($id)) {
$this->update(
$data,
array(
‘id’ => $id,
)
);
} else {
throw new Exception(“Could not find row $id”);
}
}

public function deleteGame($id)
{
$this->delete(array(
‘id’ => $id,
));
}
}

ENDS —>   

Now open your file module.php

APPLICATION_PATH/module/Game/Module.php

Add a new function  

—>   

// don’t delete your getAutoloaderConfig and getConfig method… 
 
 public function getServiceConfig() {
return array(
‘factories’ => array(
‘GameModelGameTable’ => function($sm) {
$dbAdapter = $sm->get(‘ZendDbAdapterAdapter’);
$table = new GameModelGameTable($dbAdapter);

return $table;
},
),
);
}

ENDS —>    

Now it time to replace your indexAction…
 Open a file:-

APPLICATION_PATH/module/Game/src/Game/Controller/GameController.php

 Replace your indexAction like this:-

—>  
 public function indexAction() {

return new ViewModel(array(
‘games’ => $this->getGameTable()->fetchAll(),
‘title’ => ‘Game Module’,
));
}

 ENDS —> 


Now it time to replace your indexAction…
 Open a file:-

APPLICATION_PATH/module/Game/view/game/game/index.phtml

and replace the code :-

 —> 
 

$title = ‘My Games’;
$this->headTitle($title);
?>

Add new game

Title
Edit
Delete

Type

 

 ENDS —>

[freebiesub download=”http://www.kdecom.com/wp-content/uploads/2012/10/zf2-tutorial-database-interaction.zip”]

Leave a comment

css.php