neon.config a registrace Singleton třídy
Upozornění: Tohle vlákno je hodně staré a informace nemusí být platné pro současné Nette.
- Joacim
- Člen | 229
Vytvořil jsem si třídu (model) Util
<?php
namespace App\Model;
/**
* Description of Util
*
* @author
*/
use Nette;
class Util extends \Nette\Object {
/** @inject @var Nette\Database\Context */
protected $database;
private $settings;
/* Singleton */
private static $instance;
public static function getInstance() {
if (self::$instance === NULL) {
self::$instance = new self;
}
return self::$instance;
}
private function __construct(Nette\Database\Context $database) {
$this->database = $database;
$this->setSettings();
}
private function setSettings() {
$this->settings = (object) $this->database->table('settings')->fetchPairs('name', 'value');
}
public function getSettings() {
return $this->settings;
}
}
kterou volám v BasePresenteru
abstract class BasePresenter extends Nette\Application\UI\Presenter {
/** @var settings obj */
protected $settings;
/** @inject @var Nette\Database\Context */
public $database;
/**
* @var \App\Model\Util
* @inject
*/
public $util;
public function beforeRender() {
parent::beforeRender();
if ($this->getUser()->isLoggedIn()) {
$this->template->userLogged = $this->user->identity->getId();
$this->settings = $this->util->getSettings();
$this->template->webName = $this->settings->WEB_NAME;
} else {
$this->template->userLogged = FALSE;
}
}
public function startup() {
parent::startup();
}
}
a config.neon
util: App\Model\Util::getInstance
vyhodí hlášku
Nette\DI\ServiceCreationException
Service of type App\Model\Util used in @var annotation at App\Presenters\BasePresenter::$util not found. Did you register it in configuration file?
Pokud nepoužiji sigleton vše mi funguje, ale chci použít pouze jednu instanci objektu, kterou bude zbytek dědit z base presenteru, ale možná to mám špatně navrženo a jde to řešit i jiným lepším způsobem který je mi neznámý. Každopádně jak volat static metodu getInstance ?