constr, $this->un, $this->pw); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $con; } public function __construct($constr, $un, $pw) { $this->constr = $constr; $this->un = $un; $this->pw = $pw; } public function getOneRecord($f1) { $con = $this->get_connection(); $stmt = $con->prepare('SELECT f2 FROM t1 WHERE f1 = :f1'); $stmt->execute(array(':f1' => $f1)); if($row = $stmt->fetch()) { $f2 = $row['f2']; return new Data($f1, $f2); } else { return null; } } public function getAllRecords() { $con = $this->get_connection(); $stmt = $con->prepare('SELECT f1,f2 FROM t1'); $stmt->execute(array()); $res = array(); while($row = $stmt->fetch()) { $f1 = $row['f1']; $f2 = $row['f2']; $res[] = new Data($f1, $f2); } return $res; } } class PlainPresenter implements Presenter { public function start() { // nothing } public function one($o) { echo $o->f1 . ' ' . $o->f2 . "\r\n"; } public function finish() { // nothing } } class HtmlPresenter implements Presenter { private $lbl1; private $lbl2; public function __construct($lbl1, $lbl2) { $this->lbl1 = $lbl1; $this->lbl2 = $lbl2; } public function start() { echo "\r\n"; echo "\r\n"; echo "\r\n"; echo "\r\n"; echo "\r\n"; } public function one($o) { echo "\r\n"; echo "\r\n"; echo "\r\n"; echo "\r\n"; } public function finish() { echo "
" . $this->lbl1 . "" . $this->lbl2 . "
" . $o->f1 . "" . $o->f2 . "
\r\n"; } } class StandardApplication implements Application { private $dal; private $p; public function __construct(DataAccessLayer $dal, Presenter $p) { $this->dal = $dal; $this->p = $p; } public function run() { $this->p->start(); $o = $this->dal->getOneRecord(2); $this->p->one($o); $this->p->finish(); $this->p->start(); foreach($this->dal->getAllRecords() as $o1) { $this->p->one($o1); } $this->p->finish(); } } include 'DI/functions.php'; use DI\ContainerBuilder; use function DI\create; use function DI\get; $builder = new ContainerBuilder(); $builder->addDefinitions([ Application::class => create(StandardApplication::class)->constructor(get(DataAccessLayer::class), get(Presenter::class)), //DataAccessLayer::class => create(MockDataAccessLayer::class), DataAccessLayer::class => create(DbDataAccessLayer::class)->constructor(get('constr'), get('un'), get('pw')), 'constr' => 'mysql:host=localhost;dbname=Test', 'un' => 'root', 'pw' => '', //Presenter::class => create(PlainPresenter::class), Presenter::class => create(HtmlPresenter::class)->constructor(get('lbl1'), get('lbl2')), 'lbl1' => 'F1', 'lbl2' => 'F2' ]); $cont = $builder->build(); $app = $cont->get(Application::class); $app->run(); ?>