/** * Registers a service in the services container * * @param string $name * @param mixed $definition * @param boolean $shared * @throws RuntimeException * @return \Phalcon\DI\ServiceInterface */ public static function set($name, $definition, $shared = null) { if (self::$di == null) { throw new RuntimeException('IoC container is null!'); } self::$di->set($name, $definition, $shared); }
/** * Registration services for specific module * @param \Phalcon\DI $di * @access public * @return mixed */ public function registerServices($di) { // Dispatch register $di->set('dispatcher', function () use($di) { $eventsManager = $di->getShared('eventsManager'); $eventsManager->attach('dispatch:beforeException', new \Plugins\Dispatcher\NotFoundPlugin()); $dispatcher = new \Phalcon\Mvc\Dispatcher(); $dispatcher->setEventsManager($eventsManager); $dispatcher->setDefaultNamespace('Modules\\' . self::MODULE . '\\Controllers'); return $dispatcher; }, true); // Registration of component representations (Views) $di->set('view', function () { $view = new View(); $view->setViewsDir($this->_config['application']['viewsBack'])->setMainView('auth-layout')->setPartialsDir('partials'); return $view; }); require_once APP_PATH . '/Modules/' . self::MODULE . '/config/services.php'; // call profiler if ($this->_config->database->profiler === true) { new \Plugins\Debugger\Develop($di); } if (APPLICATION_ENV == 'development') { // share Fabfuel topbar $profiler = new \Fabfuel\Prophiler\Profiler(); $di->setShared('profiler', $profiler); $pluginManager = new \Fabfuel\Prophiler\Plugin\Manager\Phalcon($profiler); $pluginManager->register(); // add toolbar in your basic BaseController } return; }
public function testProfilerInitialization() { $this->di->set(ProfilerDataCollector::DI_NAME, function () { return (new ProfilerManager())->setEventsManager($this->di->getShared('eventsManager')); }, true); $manager = $this->di->get(ProfilerDataCollector::DI_NAME); $this->assertInstanceOf('\\Vegas\\Profiler\\Manager', $manager); }
/** * @return DummyLatteTemplateAdapter */ public static function create() { $view = new PhView(); $di = new PhDi(); $di->set('tag', new PhTag()); $di->set('security', new PhSecurity()); $di->set('url', new PhUrl()); $latteFactory = new LatteFactory(); $latteFactory->setTempDir(TEMP_DIR); $adapter = new DummyLatteTemplateAdapter($view, $di, $latteFactory); return $adapter; }
/** * @param string $moduleName * @param string $modulePath */ public function register($moduleName, $modulePath) { $pPath = $this->dependencyInjection->get('config')->projectPath; $pDir = substr($pPath, 0, strlen($pPath) - 10); $relModulePath = substr($modulePath, strlen($pDir)); $x = implode('/', array_map(function () { return '..'; }, explode('/', str_replace('//', '/', $relModulePath)))); $this->view->setMainView('/../' . $x . '/common/views/index'); $this->view->setPartialsDir('/../' . $x . '/common/views/partial/'); $this->view->setViewsDir($modulePath . '/views/'); $this->registerEngine(); $this->dependencyInjection->set('view', $this->view); }
public function attachCache($cacheService) { static $mode, $collector, $hasAttachd = array(); if (in_array($cacheService, $hasAttachd)) { return; } $hasAttachd[] = $cacheService; if (!$this->shouldCollect('cache', false)) { return; } if (!is_string($cacheService)) { throw new \Exception('The parameter must be a cache service name.'); } if (!$mode) { $mode = $this->config->options->cache->get('mode', 0); } if (!$collector) { $mc = null; if ($this->hasCollector('messages')) { $mc = $this->getCollector('messages'); } $collector = new CacheCollector($mode, $mc); $this->addCollector($collector); } $backend = $this->di->get($cacheService); if ($backend instanceof Multiple || $backend instanceof Backend) { if ($this->shouldCollect('cache', false)) { $this->di->remove($cacheService); $self = $this; $this->di->set($cacheService, function () use($self, $backend, $collector) { return $self->createProxy(clone $backend, $collector); }); } } }
/** * Registration services for specific module * @param \Phalcon\DI $di * @access public * @return mixed */ public function registerServices($di) { // Dispatch register $di->set('dispatcher', function () use($di) { $eventsManager = $di->getShared('eventsManager'); $eventsManager->attach('dispatch:beforeException', function ($event, $dispatcher, $exception) { switch ($exception->getCode()) { case \Phalcon\Mvc\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND: case \Phalcon\Mvc\Dispatcher::EXCEPTION_ACTION_NOT_FOUND: $dispatcher->forward(['module' => self::MODULE, 'namespace' => 'Modules\\' . self::MODULE . '\\Controllers\\', 'controller' => 'error', 'action' => 'notFound']); return false; break; default: $dispatcher->forward(['module' => self::MODULE, 'namespace' => 'Modules\\' . self::MODULE . '\\Controllers\\', 'controller' => 'error', 'action' => 'uncaughtException']); return false; break; } }); $dispatcher = new \Phalcon\Mvc\Dispatcher(); $dispatcher->setEventsManager($eventsManager); $dispatcher->setDefaultNamespace('Modules\\' . self::MODULE . '\\Controllers'); return $dispatcher; }, true); // Registration of component representations (Views) $di->set('view', function () { $view = new View(); $view->setViewsDir($this->_config['application']['viewsFront'])->setMainView('layout'); return $view; }); return require_once APP_PATH . '/Modules/' . self::MODULE . '/config/services.php'; }
protected function _getDI() { DI::reset(); $di = new DI(); $di->set('modelsManager', function () { return new Manager(); }); $di->set('modelsMetadata', function () { return new Memory(); }); $di->set('db', function () { require PATH_CONFIG . 'config.db.php'; return new Mysql($configMysql); }); return $di; }
/** * Return flash instance */ protected function getFlash() { $flash = new PhFlash($this->classes); $di = new PhDI(); $di->set('session', new Helper\InMemorySession(), true); $flash->setDI($di); return $flash; }
private function getDi() { $di = new PhalconDi(); $di->set('request', function () { return new PhalconRequest(); }); return $di; }
public static function setUpBeforeClassAndDataProviders() { self::$previousDependencyInjector = DI::getDefault(); $di = new DI(); $di->set('modelsMetadata', function () { return new MemoryMetadata(); }, true); $di->set('modelsManager', function () { return new ModelsManager(); }, true); $di->set('db', function () { return new MysqlAdapter(array('host' => 'localhost', 'port' => '3306', 'username' => 'root', 'password' => '', 'dbname' => 'incubator_tests', 'charset' => 'utf8mb4')); }, true); if (self::$previousDependencyInjector instanceof DI) { DI::setDefault($di); } spl_autoload_register(array(__CLASS__, 'autoloadModels'), true, true); }
/** * Initializes the request object and returns it * * @author Nikolaos Dimopoulos <*****@*****.**> * @since 2014-10-05 * * @return PhRequest */ protected function getRequestObject() { PhDI::reset(); $di = new PhDI(); $di->set('filter', function () { return new PhTFilter(); }); $request = new PhTRequest(); $request->setDI($di); return $request; }
/** * Initialize testing object * * @uses Auth * @uses \ReflectionClass */ public function setUp() { $this->di = new FactoryDefault(); $this->di->reset(); // Setup DI $this->di = new DI(); $this->di->setShared('session', function () { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $this->di->set('tag', function () { $tag = new \Phalcon\Tag(); return $tag; }); $this->di->set('escaper', function () { $escaper = new \Phalcon\Escaper(); return $escaper; }); DI::setDefault($this->di); $this->reflection = new \ReflectionClass('ULogin\\Auth'); $this->auth = new Auth(); }
/** * @param DI $di */ public function registerServices($di) { $this->registerAutoloaders(); $di->setShared('session', function () { $session = new \Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); $di->set('view', function () use($di) { $view = new View(); $view->setViewsDir(MINI_ADMIN_ROOT . '/views/'); return $view; }); }
/** * Sets the test up by loading the DI container and other stuff * * @author Nikos Dimopoulos <*****@*****.**> * @since 2012-09-30 * * @param \Phalcon\DiInterface $di * @param \Phalcon\Config $config * @return DI */ protected function setUp(DiInterface $di = null, Config $config = null) { $this->checkExtension('phalcon'); if (!is_null($config)) { $this->config = $config; } if (is_null($di)) { // Reset the DI container DI::reset(); // Instantiate a new DI container $di = new DI(); // Set the URL $di->set('url', function () { $url = new Url(); $url->setBaseUri('/'); return $url; }); $di->set('escaper', function () { return new \Phalcon\Escaper(); }); } $this->di = $di; }
/** * This methods registers the services to be used by the application */ protected function registerServices() { $di = new DI(); //Registering a router $di->set('router', function () { return new Router(); }); //Registering a dispatcher $di->set('dispatcher', function () { $dispatcher = new Dispatcher(); $dispatcher->setDefaultNamespace('Single\\Controllers\\'); return $dispatcher; }); //Registering a Http\Response $di->set('response', function () { return new Response(); }); //Registering a Http\Request $di->set('request', function () { return new Request(); }); //Registering the view component $di->set('view', function () { $view = new View(); $view->setViewsDir('../apps/views/'); return $view; }); $di->set('db', function () { return new Database(array("host" => "localhost", "username" => "root", "password" => "", "dbname" => "invo")); }); //Registering the Models-Metadata $di->set('modelsMetadata', function () { return new MemoryMetaData(); }); //Registering the Models Manager $di->set('modelsManager', function () { return new ModelsManager(); }); $this->setDI($di); }
/** * Inicializa os serviços de CDN * * @param $di * Dependence Injetion Manager do Phalcon * * * @param $extension * Extensão do arquivo que sobrescreve as configurações com extensão .global * no caso de testes passamos o parametro como 'test', possibilidades atuais ('local', 'test', 'global') */ public static function init(\Phalcon\DI $di, $extension = 'local') { //se estiver rodando testes if ($extension == 'test') { if (!file_exists(__DIR__ . '/../config/base_url.test.php')) { throw new \Exception("Arquivo base_url.test.php nao existe"); } } //verifica configuracoes locais $config = (include file_exists(__DIR__ . '/../config/base_url.' . $extension . '.php') ? __DIR__ . '/../config/base_url.' . $extension . '.php' : __DIR__ . '/../config/base_url.global.php'); if (isset($config['base_url']) && $config['base_url']) { foreach ($config['base_url'] as $k => $base_url) { $name = 'base_url_' . $k; //adiciona as configurações de CDN $di->set($name, function () use($base_url) { return $base_url; }); } } }
public function __construct(DI $di, $aggregate = true, $formatter = 'line') { $this->_di = $di; $this->_debugbar = $this->_di['debugbar']; $this->_formatter = strtolower($formatter); if ($di->has('log') && ($log = $di->get('log'))) { $debugbar_loger = new Debugbar($di['debugbar']); if ($log instanceof Adapter) { $di->remove('log'); $multiple = new Multiple(); $multiple->push(clone $log); $multiple->push($debugbar_loger); /** @var DI\Service $service */ $di->set('log', $multiple); } elseif ($log instanceof Multiple) { $log->push($debugbar_loger); } $this->_aggregate = $this->isAggregate($aggregate); } }
public function testRegisterView() { $view = \Mockery::mock('mirolabs\\phalcon\\Framework\\View\\View')->shouldDeferMissing()->makePartial(); $dependencyInjection = new DI(); $modulePath = 'projectPath/modules'; $moduleName = 'test'; $config = new Map(); $config->set('view', json_encode(['compiledPath' => 'compiledPath', 'compiledSeparator' => 'compiledSeparator', 'compiledExtension' => '.compile', 'compileAlways' => true, 'stat' => 'stat'])); $config->set('projectPath', '"projectPath"'); $config->set('environment', '"dev"'); $config->set('ng.app.name', '"ngtest"'); $dependencyInjection->set('config', $config); $view->shouldReceive('setViewsDir')->with($modulePath . '/views/')->once(); $view->shouldReceive('registerEngines')->once(); $view->shouldReceive('setRenderLevel')->with(View::LEVEL_ACTION_VIEW)->once(); $view->shouldReceive('setVar')->with('ngAppName', 'ngtest')->once(); $view->shouldReceive('setDI'); $registerView = new RegisterView($view, $dependencyInjection); $registerView->register($moduleName, $modulePath); $view->mockery_verify(); $this->assertEquals($view, $dependencyInjection->get('view')); }
<?php use Phalcon\DI, Phalcon\Db\Adapter\Pdo\Sqlite as Connection, Phalcon\Mvc\Model\Manager as ModelsManager, Phalcon\Mvc\Model\Metadata\Memory as MetaData, Phalcon\Mvc\Model; $di = new DI(); //Setup a connection $di->set('db', new Connection(array("dbname" => "sample.db"))); //Set a models manager $di->set('modelsManager', new ModelsManager()); //Use the memory meta-data adapter or other $di->set('modelsMetadata', new MetaData()); //Create a model class Robots extends Model { } //Use the model echo Robots::count();
/** * Init Redis to usse in socket.io. * * @param DI $di Dependency Injection. * @param Config $config Config object. * * @return void */ protected function _initRedis($di, $config) { $di->set('redis', function () use($config) { $redis = new \Redis(); $redis->connect($config->db->redis->host, $config->db->redis->port); return $redis; }, true); }
/** * Init cache. * * @param DI $di Dependency Injection. * @param Config $config Config object. * * @return void */ protected function _initCache($di, $config) { $caches['cache'] = $config->cache->toArray(); if (!empty($config->cacheSlave)) { foreach ($config->cacheSlave as $cache) { $caches['cacheSlave'][] = $cache->toArray(); } } $adapter = ucfirst($config->cache->adapter); if ($adapter == "Redis") { $cacheAdapter = '\\Engine\\' . $adapter; } else { $cacheAdapter = '\\Phalcon\\Cache\\Backend\\' . $adapter; } $frontEndOptions = ['lifetime' => $config->cache->lifetime]; $cacheDataAdapter = new $cacheAdapter($frontEndOptions, $caches); $di->set('cacheData', $cacheDataAdapter, true); }
/** * This methods registers the services to be used by the application */ protected function _registerServices() { $di = new DI(); //Registering a router $di->set('router', function () { $router = new MvcRouter(); $router->setUriSource(MvcRouter::URI_SOURCE_SERVER_REQUEST_URI); foreach (include ROOT_DIR . "/config/router.php" as $key => $value) { $router->add($key, $value); } return $router; }); //Registering a dispatcher $di->set('dispatcher', function () { //Create an EventsManager $eventsManager = new EventsManager(); //Attach a listener $eventsManager->attach("dispatch", function ($event, $dispatcher, $exception) { //Handle controller or action doesn't exist if ($event->getType() == 'beforeException') { switch ($exception->getCode()) { case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND: case Dispatcher::EXCEPTION_ACTION_NOT_FOUND: $dispatcher->forward(['controller' => 'error', 'action' => 'index', 'params' => ['message' => $exception->getMessage()]]); return false; } } }); $dispatcher = new MvcDispatcher(); $dispatcher->setDefaultNamespace('App\\Controllers\\'); $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); //Registering a Http\Response $di->set('response', function () { return new Response(); }); //Registering a Http\Request $di->set('request', function () { return new Request(); }); //Registering the view component $di->set('view', function () { $view = new MvcView(); $view->setViewsDir(ROOT_DIR . '/app/Views/'); return $view; }); /*$di->set('view', function(){ $view = new MvcView(); $view->setViewsDir(ROOT_DIR . '/app/Views/'); $view->registerEngines([ '.html' => function($view, $di) { $smarty = new \Phalbee\Base\View\Engine\Smarty($view, $di); $smarty->setOptions([ 'left_delimiter' => '<{', 'right_delimiter' => '}>', 'template_dir' => ROOT_DIR . '/app/Views', 'compile_dir' => ROOT_DIR . '/runtime/Smarty/compile', 'cache_dir' => ROOT_DIR . '/runtime/Smarty/cache', 'error_reporting' => error_reporting() ^ E_NOTICE, 'escape_html' => true, 'force_compile' => false, 'compile_check' => true, 'caching' => false, 'debugging' => true, ]); return $smarty; }, ]); return $view; });*/ $di->set('smarty', function () { $smarty = new \Smarty(); $options = ['left_delimiter' => '<{', 'right_delimiter' => '}>', 'template_dir' => ROOT_DIR . '/app/Views', 'compile_dir' => ROOT_DIR . '/runtime/Smarty/compile', 'cache_dir' => ROOT_DIR . '/runtime/Smarty/cache', 'error_reporting' => error_reporting() ^ E_NOTICE, 'escape_html' => true, 'force_compile' => false, 'compile_check' => true, 'caching' => false, 'debugging' => true]; foreach ($options as $k => $v) { $smarty->{$k} = $v; } return $smarty; }); $di->set('db', function () { $db = (include ROOT_DIR . "/config/db.php"); return new Database($db); }); //Registering the Models-Metadata $di->set('modelsMetadata', function () { return new MvcModelMetadataMemory(); }); //Registering the Models Manager $di->set('modelsManager', function () { return new MvcModelsManager(); }); $this->setDI($di); }
#!/usr/bin/env php <?php use Phalcon\Queue\Beanstalk; use Phalcon\Queue\Beanstalk\Job; use Phalcon\DI; use SlowProg\Mailer\MailerService; // Подключаем конфиг приложения (исправить на свой) $config = (require __DIR__ . '/app/config/config.php'); $di = new DI(); $di->set('config', $config); $queue = new Beanstalk(); $queue->choose('mailer'); $di['queue'] = $queue; /** * Register Mailer Service */ $di['mailer'] = function () { $service = new MailerService(); return $service->mailer(); }; /** @var Job $job */ while (($job = $queue->peekReady()) !== false) { $data = json_decode($job->getBody(), true); $segments = explode(':', $data['job']); if (count($segments) !== 2) { continue; } call_user_func_array([$di[$segments[0]], $segments[1]], [$job, $data['data']]); }
public function testFilterMultiplesSourcesFilterJoin() { $this->markTestIncomplete('To be checked'); @unlink('unit-tests/assets/production/combined-3.js'); Phalcon\DI::reset(); $di = new Phalcon\DI(); $di['url'] = function () { $url = new Phalcon\Mvc\Url(); $url->setStaticBaseUri('/'); return $url; }; $di->set('escaper', function () { return new \Phalcon\Escaper(); }); $assets = new PhTAssetsManager(); $assets->useImplicitOutput(false); $js = $assets->collection('js'); $js->setTargetUri('production/combined-3.js'); $js->setTargetPath('unit-tests/assets/production/combined-3.js'); $jquery = new PhTAssetsResourceJs('unit-tests/assets/jquery.js', false, false); $jquery->setTargetUri('jquery.js'); $js->add($jquery); $gs = new PhTAssetsResourceJs('unit-tests/assets/gs.js'); $gs->setTargetUri('gs.js'); $gs->setTargetPath('gs.js'); $js->add($gs); $js->join(true); //Use two filters $js->addFilter(new Phalcon\Assets\Filters\None()); $js->addFilter(new Phalcon\Assets\Filters\None()); $this->assertEquals($assets->outputJs('js'), '<script type="text/javascript" src="/production/combined-3.js"></script>' . PHP_EOL); }
/** * Register routers * * @access private * @param Phalcon\DI $di */ private function registerRouters($di) { $di->set('collections_' . self::MODULE, function () { return include __DIR__ . '/routes/loader.php'; }); }
/** * @expectedException \Phalcon\Mvc\Model\Exception * @expectedExceptionMessage Field name must be a string */ public function testValidateIncorrectFieldType() { $di = new DI(); $di->set('modelsManager', new Manager()); require_once __DIR__ . '/resources/TestCardNumberIncorrectField.php'; $obj = new \TestCardNumberIncorrectField(); $obj->validation(); }
/** * Init locale. * * @param DI $di Dependency injection. * @param Config $config Dependency injection. * * @return void */ protected function _initI18n(DI $di, Config $config) { if ($di->get('app')->isConsole()) { return; } $languageObject = null; if (!$di->get('session')->has('language')) { /** @var Language $languageObject */ if ($config->installed) { $language = Settings::getSetting('system_default_language'); if ($language == 'auto') { $locale = \Locale::acceptFromHttp($_SERVER["HTTP_ACCEPT_LANGUAGE"]); $languageObject = Language::findFirst("language = '" . $locale . "' OR locale = '" . $locale . "'"); } else { $languageObject = Language::findFirst("language = '" . $language . "'"); } } if ($languageObject) { $di->get('session')->set('language', $languageObject->language); $di->get('session')->set('locale', $languageObject->locale); } else { $di->get('session')->set('language', Config::CONFIG_DEFAULT_LANGUAGE); $di->get('session')->set('locale', Config::CONFIG_DEFAULT_LOCALE); } } $language = $di->get('session')->get('language'); $translate = null; if (!$config->application->debug || !$config->installed) { $messages = []; $directory = $config->application->languages->cacheDir; $extension = ".php"; if (file_exists($directory . $language . $extension)) { require $directory . $language . $extension; } else { if (file_exists($directory . Config::CONFIG_DEFAULT_LANGUAGE . $extension)) { // fallback to default require $directory . Config::CONFIG_DEFAULT_LANGUAGE . $extension; } } $translate = new TranslateArray(["content" => $messages]); } else { if (!$languageObject) { $languageObject = Language::findFirst(['conditions' => 'language = :language:', 'bind' => ["language" => $language]]); if (!$languageObject) { $languageObject = Language::findFirst("language = '" . Config::CONFIG_DEFAULT_LANGUAGE . "'"); } } $translate = new TranslationDb($di, $languageObject->getId(), new LanguageTranslation()); } $di->set('i18n', $translate); }
public function testValidateCustomMessage() { $di = new DI(); $di->set('modelsManager', new Manager()); require_once __DIR__ . '/resources/TestBetweenModel.php'; $obj = new \TestBetweenModel(); $obj->min = 1; $obj->max = 2; $obj->position = 3; $obj->message = 'test 123'; $obj->validation(); $messages = $obj->getMessages(); $this->assertEquals($messages[0]->getMessage(), 'test 123'); }
/** * Init flash messages. * * @param DI $di Dependency Injection. * * @return void */ protected function _initFlash($di) { $flashData = ['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info']; $di->set('flash', function () use($flashData) { $flash = new FlashDirect($flashData); return $flash; }); $di->set('flashSession', function () use($flashData) { $flash = new FlashSession($flashData); return $flash; }); }