Skip to content

Instantly share code, notes, and snippets.

@Majkl578
Created July 11, 2011 19:25
Show Gist options
  • Save Majkl578/1076590 to your computer and use it in GitHub Desktop.
Save Majkl578/1076590 to your computer and use it in GitHub Desktop.
Nette: Dynamické načítání modelů - Dibi + Nette\DI
<?php
namespace Models;
/**
* Base model
* @link http://wiki.nette.org/cs/cookbook/dynamicke-nacitani-modelu
* @author Majkl578
*/
abstract class Base extends \Nette\Object
{
/** @var \Nette\DI\Container */
private $context;
public function __construct(\Nette\DI\Container $container)
{
$this->context = $container;
}
/**
* @return \Nette\DI\Container
*/
final public function getContext()
{
return $this->context;
}
/**
* @return \DibiConnection
*/
final public function getDatabase()
{
return $this->context->database;
}
}
<?php
/**
* Base presenter
* @link http://wiki.nette.org/cs/cookbook/dynamicke-nacitani-modelu
* @author Majkl578
*/
abstract class BasePresenter extends \Nette\Application\UI\Presenter
{
public function actionFoo()
{
$this->models->foo; //instanceof Models\Foo
}
/**
* @return \ModelLoader
*/
final public function getModels()
{
return $this->context->modelLoader;
}
}
common:
php:
date.timezone: Europe/Prague
#parametry pro připojení k databázi
database:
hostname: local
username: root
password:
database: foo
charset: utf8
#parametry pro modely
models:
foo: bar
services:
robotLoader:
run: true
database:
class: DibiConnection
arguments: [%database%]
modelLoader:
class: ModelLoader
arguments: [@container]
production < common:
development < common:
<?php
namespace Models;
class Foo extends Base
{
public function bar()
{
//return $this->getDatabase()->...;
}
}
<?php
use Nette\DI\Container;
/**
* Model loader
* @link http://wiki.nette.org/cs/cookbook/dynamicke-nacitani-modelu
* @author Majkl578
*/
final class ModelLoader
{
/** @var Nette\DI\Container */
private $modelContainer;
/** @var array */
private $models = array();
public function __construct(Container $container)
{
$modelContainer = new Container;
$modelContainer->addService('database', $container->database);
$modelContainer->addService('cacheStorage', $container->cacheStorage);
$modelContainer->addService('session', $container->session);
$modelContainer->params = $container->params['models'];
$modelContainer->freeze();
$this->modelContainer = $modelContainer;
}
public function getModel($name)
{
$lname = strtolower($name);
if (!isset($this->models[$lname])) {
$class = 'Models\\' . ucfirst($name);
if (!class_exists($class)) {
throw new \InvalidArgumentException("Model '$class' not found");
}
$this->models[$lname] = new $class($this->modelContainer);
}
return $this->models[$lname];
}
public function __get($name)
{
return $this->getModel($name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment