Search code examples
phpzend-framework2zend-framework-modules

zend framework 2 model/adapter reusable


I have a model which is used by two modules. I don't want to duplicate the code for that model into each modules.

For example I have 2 modules. First takes the blog posts from model and print them for normal users, and the other one prints them for admin users but with a few more options (which are set in the view). I would have the same model in two places. And.. that's bad.

Just a piece of code:

<?php
namespace Blog\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;
class BlogTable extends AbstractTableGateway
{
    protected $table = 'blog_posts';
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->initialize();
    }
    /**
     * Gets the blog post list
     *
     * @return array
     **/
    public function fetchAll()
    {
        //..
    }
}

So, how should I design this application?


Solution

  • The biggest question might be why you separate the administrative side outside of the 'Blog-Scope'. An administrative Module should only be the front-end to gather all backend-options (if that makes any sense)

    However to get back into your question: you can simply include those classes from model A into model B, like use Blog\Model\BlogTable

    Ultimately though i see management of a module as a responsible of the Blog-Module itself, as hinted within the first paragraph.

    Edit: One thing i forgot to mention. Ideally if you decide to go the dependant approach, your module should make the BlogTable accessible through a service. That way your ModuleAdmin only has to do something like $serviceLocator->get('my-blog-table') which is a much more clean approach.