C
C
Cat Anton2014-11-29 21:34:58
Zend Framework
Cat Anton, 2014-11-29 21:34:58

How can code be rewritten using ServiceManager or DI?

Module (\module\Application\Module.php):

namespace Application;

use Zend\Db\Adapter\Adapter;

class Module
{
    static protected $adapter;

    static public function getAdapter()
    {
        if (!isset(static::$adapter))
        {
            static::$adapter = new Adapter(array(
                'driver' => 'Mysqli',
                'database' => 'data',
                'username' => 'root',
                'password' => '',
            ));
        }

        return static::$adapter;
    }
}

Abstract data model class (\module\Application\src\Application\Model.php):
namespace Application;

abstract class Model
{
    static public $instances = array();
    
    public function __construct($id)
    {
        $adapter = Module::getAdapter();
        $table = static::$table;
        
        // Получение данных из таблицы $table по $id
    }

    static public function getInstance($id)
    {
        $class = get_called_class();
        if (!array_key_exists($class, static::$instances)) {
            static::$instances[$class] = array();
        }

        if (!array_key_exists($id, self::$instances[$class])) {
            static::$instances[$class][$id] = new static($id);
        }

        return static::$instances[$class][$id];
    }
}

User (\module\Application\src\Application\Model\User.php):
namespace Application\Model;

use Application\Model;

class User extends Model
{
    static public $table = 'users';    
}

- The abstract class Model must have access to the database adapter;
- All created models must be in one copy (singletons), just don't write about how bad it is :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Chukhlomin, 2015-12-31
@27cm

Start by saying that a Module doesn't need to know how to create an Adapter. That the Model should explicitly depend on the Module (and probably should not know anything about the Adapter).
There was a very good article on Habré: Inversion of Control: Implementation methods with examples... I
also advise you to read: Are Static Methods/Variables bad practice?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question