Answer the question
In order to leave comments, you need to log in
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;
}
}
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];
}
}
namespace Application\Model;
use Application\Model;
class User extends Model
{
static public $table = 'users';
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question