Nathaniel Wendt
Nathaniel Wendt

Reputation: 1204

Zend Simple View-Controller-Model Guidelines

I am new to Zend framework. I am having a controller interact with a model and then send that information to the view.

Currently my code looks something like this:

//Controller
$mapper = new Application_Model_Mapper();
$mapper->getUserById($userID);      
$this->view->assign('user_name', $mapper->user_name);
$this->view->assign('about', $mapper->about;
$this->view->assign('location', $mapper->location);

//Model
class Application_Model_Mapper
{
    private $database;
    public $user_name;
    public $about;
    public $location;

public function __construct()
{
    $db = new Application_Model_Dbinit;
        $this->database = $db->connect;
}

public function getUserById($id)
{
    $row = $this->database->fetchRow('SELECT * FROM my_table WHERE user_id = '. $id .'');
    $this->user_name = $row['user_name'];
    $this->about = $row['about'];
    $this->location = $row['location'];
}

}

//View
<td><?php echo $this->escape($this->user_name); ?> </td>
<td><?php echo $this->escape($this->about); ?></td>
<td><?php echo $this->escape($this->location); ?></td>

That code is obviously not in entirety but you can imagine how I am trying to operate with the model. I am wondering if this is a good Zend coding strategy?

I am wondering because if I had more data to pull from the model, the controller starts getting quite large (one line per item) and the model has a lot of public data members.

I can't help but think there is a better way, but I am trying to avoid having the view access the model directly.

Upvotes: 0

Views: 1064

Answers (2)

JohnP
JohnP

Reputation: 50009

You should be working with complete objects rather than breaking down and reconstructing them by attributes.

Zend has a DB abstraction layer that you can use to quickly work through it. Have a look at these

http://framework.zend.com/manual/en/zend.db.html http://framework.zend.com/manual/en/zend.db.table.html

As a starting point, start passing complete (preferable data transfer) objects to the view.

//This is just a simple example, I'll leave it up to you how you want to organize your models. You can use several strategies. At work we use the DAO pattern. 
$user = $userModel->getUser($id);
$this->view->user  = $user;

And in your view,

Name : <?=$this->user->name?> <br>
About me : <?=$this->user->about?> <br>

Upvotes: 1

Mr Coder
Mr Coder

Reputation: 8186

Check these slides by ZF team lead about modelling your objects.

http://www.slideshare.net/weierophinney/playdoh-modelling-your-objects

Upvotes: 2

Related Questions