Messing around with the Zend Framework and just wondering how everyone is handleing the model when it comes to the mvc part of the framework. This is what i have so far. Not new to OOP but still have some way to go. Any insight would be greatly appreciated.
I removed the view (html) from this as well as the comments to save space since its pretty straight forward at this stage and the main goal i hope to accomplish is get input on how people are passing the model into the controller.
index.php (Index)
PHP Code:<?php
require_once 'Zend.php';
function __autoload($class)
{
Zend::loadClass($class);
}
$config = new Zend_Config(Zend_Config_Xml::load('../app/config/config.xml', 'production'));
$params = array('host' => $config->database->host,
'username' => $config->database->username,
'password' => $config->database->password,
'dbname' => $config->database->name);
$db = Zend_Db::factory('PDO_MYSQL', $params);
Zend::register('db', $db);
$router = new Zend_Controller_RewriteRouter();
$router->addRoute('user', 'users/:username', array('controller' => 'users', 'action' => 'index'));
$ctrl = Zend_Controller_Front::getInstance();
$ctrl->setControllerDirectory('../app/controllers/');
$ctrl->setRouter($router);
$ctrl->dispatch();
UsersController.php (Controller)
PHP Code:<?php
require_once '../app/models/Users.php';
class UsersController extends Zend_Controller_Action
{
private $_users;
private $_view;
public function __construct()
{
$this->_users = new Users();
$this->_view = new Zend_View();
$this->_view->setScriptPath('../app/views/');
}
public function indexAction()
{
$params = $this->_getAllParams();
if ($params['username']) {
$this->infoAction();
} else {
$this->_view->users = $this->_users->getUsers();
echo($this->_view->render('users.php'));
}
}
private function infoAction()
{
$this->_view->userInfo = $this->_users->getInfo();
echo($this->_view->render('userInfo.php'));
}
}
Users.php (Model)
PHP Code:<?php
class Users
{
private $_db;
public function __construct()
{
$this->_db = Zend::registry('db');
}
public function getUsers()
{
$sql = "SELECT user
FROM users";
if ($result = $this->_db->query($sql)) {
return $result->fetchAll();
}
}
public function getInfo()
{
$sql = "SELECT first_name, last_name
FROM users";
if ($result = $this->_db->query($sql)) {
return $result->fetchAll();
}
}
}




Bookmarks