Skip to content

Instantly share code, notes, and snippets.

@fprochazka
Created May 17, 2011 08:30
Show Gist options
  • Save fprochazka/976155 to your computer and use it in GitHub Desktop.
Save fprochazka/976155 to your computer and use it in GitHub Desktop.
Psáno na aktuální Nette (master - 50c3c40)
<?php
abstract class BaseModel extends Nette\Object
{
/** @var NotORM */
protected $connection;
/**
* @param NotORM
*/
public function __construct(NotORM $connection)
{
$this->connection = $connection;
}
}
common:
service:
connection: App\MyServiceFactories::createServiceConnection
models: App\MyServiceFactories::createServiceModels
development < common:
database:
engine: mysql
host: localhost
database: foo
username: foo
password: bar
charset: utf8
<?php
class FooModel extends BaseModel
{
public function find($id)
{
// ...
return $result;
}
}
<?php
class FooPresenter extends BasePresenter
{
protected $foo = NULL;
public function actionDetail($id)
{
// tady přibyla jedna property v řetězci
// Models je Locator na všechny služby v MyModelsLocator
$this->foo = $this->context->models->foo->find($id);
if (!$this->foo) {
throw new \Nette\Application\BadRequestException("Foo with id $id not found");
}
}
public function renderDetail()
{
$this->template->foo = $this->foo;
}
}
<?php
/**
* @property-read FooModel $foo
*/
class MyModelsLocator extends Nette\DI\Container
{
protected function createServiceFoo()
{
// všimni si že služba container se sem dostane v továrničce v MyServiceFactories
return new FooModel($this->container->connection);
}
// ...
}
<?php
class MyServiceFactories
{
public static function createServiceConnection(IContainer $container)
{
$db = $container->config['database'];
$pdo = new PDO("{$db['engine']}:host={$db['host']};dbname={$db['database']}", $db['username'], $db['password']);
if (isset($db['charset'])) {
$pdo->exec("SET CHARACTER SET " . $db['charset']);
}
return new NotORM($pdo);
}
public static function createServiceModels(IContainer $container)
{
$models = new MyModelsLocator();
$models->addService('container', $container); // kvůli connection, globálním službám, ...
return $models;
}
}
// .., app run
@Mikulas
Copy link

Mikulas commented May 17, 2011

A když těch modelů bude víc? Dá se teď v Nette udělat ta registrace automaticky? Tzn. aby pro každý model nemusel být kód createServiceFoo a definice v config.neon?

@fprochazka
Copy link
Author

Máš spoustu možností

@Mikulas
Copy link

Mikulas commented May 17, 2011

Díky, už tomu začínám přicházet na chuť : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment