public function resolve(\Phalcon\Config $config) { $di = new \Phalcon\Di\FactoryDefault(); $di->set('config', $config, true); $di->set('mongo', function () use($config) { $connectionString = "mongodb://{$config->mongo->host}:{$config->mongo->port}"; $mongo = new \MongoClient($connectionString); return $mongo->selectDb($config->mongo->dbname); }, true); $di->set('collectionManager', function () { return new \Phalcon\Mvc\Collection\Manager(); }, true); \Phalcon\Di::setDefault($di); }
public function setConfig($file) { if (!file_exists($file)) { throw new \Exception('Unable to load phalcon config file'); } $di = new \Phalcon\Di\FactoryDefault(); $config = new \Phalcon\Config(require $file); $di->set('config', $config); $di->set('db', function () use($config) { return new \Phalcon\Db\Adapter\Pdo\Mysql(array('adapter' => $config['database']['adapter'], 'host' => $config['database']['host'], 'username' => $config['database']['username'], 'password' => $config['database']['password'], 'dbname' => $config['database']['name'], 'port' => $config['database']['port'])); }); $di->set('elements', function () { return new \Elements\Elements(); }); $this->setDI($di); }
/** * @param array $config * @return \Phalcon\Di\FactoryDefault */ public static function createMvcFrom(array $config) : \Phalcon\Di\FactoryDefault { $di = new \Phalcon\Di\FactoryDefault(); $di->set('config', function () use($config) { return new Config($config); }); $di->setShared('router', function () use($config) { return Router::createFrom($config['routes'] ?? []); }); $di->setShared('dispatcher', function () use($config) { return Dispatcher::createMvcFrom($config['dispatcher']); }); if (isset($config['view'])) { $di->setShared('view', function () use($config, $di) { return View::createFrom($config['view'] ?? [], $di); }); } foreach ($config['services'] ?? [] as $service) { /** @var InjectableInterface $service */ $service::injectTo($di); } return $di; }
<?php try { //Read the configuration $config = new Phalcon\Config\Adapter\Ini('../app/config/config.ini'); //Register an autoloader $loader = new Phalcon\Loader(); $loader->registerDirs(array('../', '../' . $config->application->controllersDir, '../' . $config->application->modelsDir)); $loader->register(); //Create a DI $di = new Phalcon\Di\FactoryDefault(); // Коннект к базе данных создается соответственно параметрам в конфигурационном файле $di->set('db', function () use($config) { return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname)); }); $di->set('dispatcher', function () use($di) { // Получаем стандартный менеджер событий с помощью DI $eventsManager = $di->getShared('eventsManager'); // Инстанцируем плагин безопасности $security = new Core_UserCenter_Security($di); // Плагин безопасности слушает события, инициированные диспетчером $eventsManager->attach('dispatch', $security); $dispatcher = new Phalcon\Mvc\Dispatcher(); // Связываем менеджер событий с диспетчером $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); //Setting up the view component $di->set('view', function () use($config) { $view = new Phalcon\Mvc\View(); $view->setViewsDir('../' . $config->application->viewsDir);
} catch (MongoConnectionException $e) { $logger->error("Error al intentar conectar a mongo"); $logger->error($e->getMessage()); $logger->error(MDB_CONN_STRING); die("MongoDB error: {$e->getMessage()}"); } catch (Exception $e) { $logger->error($e->getMessage()); die("MongoDB error: {$e->getMessage()}"); } //Set Mysql and models // Use Loader() to autoload our models $loader = new \Phalcon\Loader(); $loader->registerDirs(array(__DIR__ . '/models/'))->register(); //Set up the database service, values set in config.php $di->set('db', function () { return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => MYSQL_HOST, "username" => MYSQL_USER, "password" => MYSQL_PASS, "dbname" => MYSQL_DB_NAME)); }); /** * Default routes */ $app->get("/", function () use($app, $mongo) { $mdb = $mongo->selectDB(MDB_DB_NAME); $books = $mdb->selectCollection(MDB_COLLECTION); $json = array("version" => VERSION, "mongodb" => 'ok', "collection" => $books->getName(), "db" => "ok", "routes" => array()); foreach ($app->router->getRoutes() as $route) { $json["routes"][] = $route->getPattern(); } echo "<pre>"; echo json_encode($json, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES); echo "</pre>"; });
]); $loader->registerClasses([ 'Component\User'=>'../app/components/User.php', 'Component\Helper'=>'../app/components/Helper.php', ]); $loader->register(); //Dependency Injection $di=new \Phalcon\Di\FactoryDefault(); //Set Base URL $di->set('url', function() { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri('http://localhost/xampp/phalcon-learning/'); return $url; }, true); //Database $di->set('db',function(){ $db=new \Phalcon\Db\Adapter\Pdo\Mysql([ 'host'=>'localhost', 'username'=>'root', 'password'=>'', 'dbname'=>'phalcon-learning' ]); return $db; }); //Load Views
<?php try { //Read the configuration $config = new Phalcon\Config\Adapter\Ini('../app/config/config.ini'); //Register an autoloader $loader = new Phalcon\Loader(); $loader->registerDirs(array('../', '../' . $config->application->controllersDir, '../' . $config->application->modelsDir)); $loader->register(); //Create a DI $di = new Phalcon\Di\FactoryDefault(); // Коннект к базе данных создается соответственно параметрам в конфигурационном файле $di->set('db', function () use($config) { return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname)); }); //Setting up the view component $di->set('view', function () use($config) { $view = new Phalcon\Mvc\View(); $view->setViewsDir('../' . $config->application->viewsDir); return $view; }); // Сессии запустятся один раз, при первом обращении к объекту $di->setShared('session', function () { $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; }); //Handle the request $application = new \Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (\Phalcon\Exception $e) {
<?php /** * File Description * User: Kp * Date: 2015/10/21 * Time: 15:00 */ define('ROOT_PATH', dirname(__DIR__)); $loader = new \Phalcon\Loader(); $loader->registerDirs(array(ROOT_PATH . '/application/controller/', ROOT_PATH . '/application/model/')); $loader->register(); $di = new \Phalcon\Di\FactoryDefault(); //Registering the view component $di->set('view', function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(ROOT_PATH . '/application/views/'); return $view; }); try { $application = new \Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (Exception $e) { echo $e->getMessage(); }
<?php if (!extension_loaded('phalcon')) { die('Phalcon not installed in your server. Follow the link: https://github.com/phalcon/cphalcon#linuxunixmac'); } error_reporting(E_ALL); ini_set('display_errors', 'On'); include_once '../vendor/autoload.php'; $container = new \Phalcon\Di\FactoryDefault(); $container->set('auth', function () { $auth = new \PhalconDez\Auth\Auth(new \PhalconDez\Auth\Adapter\Session()); $auth->setCredentialsModel(new \PhalconDez\Auth\Model\Credentials()); $auth->setSessionModel(new \PhalconDez\Auth\Model\Session()); $auth->initialize(); return $auth; }); $container->set('cookies', function () { $cookies = new \Phalcon\Http\Response\Cookies(); $cookies->useEncryption(false); return $cookies; }); $container->setShared('session', function () { $session = new \Phalcon\Session\Adapter\Files(); $session->setName('phalcon_session'); $session->start(); return $session; }); $container->set('crypt', function () { $crypt = new \Phalcon\Crypt(); $crypt->setMode(MCRYPT_MODE_CFB); $crypt->setKey('%31.1e$i86e$f!8j');
/** * Executes the web tool application * * @param string $path */ public static function main($path) { chdir('..'); if (!extension_loaded('phalcon')) { throw new \Exception('Phalcon extension isn\'t installed, follow these instructions to install it: http://phalconphp.com/documentation/install'); } //Read configuration $configPath = "app/config/config.ini"; if (file_exists($configPath)) { $config = new \Phalcon\Config\Adapter\Ini($configPath); } else { $configPath = "app/config/config.php"; if (file_exists($configPath)) { $config = (require $configPath); } else { throw new \Phalcon\Exception('Configuration file could not be loaded'); } } $loader = new \Phalcon\Loader(); $loader->registerDirs(array($path . '/scripts/', $path . '/scripts/Phalcon/Web/Tools/controllers/')); $loader->registerNamespaces(array('Phalcon' => $path . '/scripts/')); $loader->register(); if (Version::getId() < Script::COMPATIBLE_VERSION) { throw new \Exception('Your Phalcon version isn\'t compatible with Developer Tools, download the latest at: http://phalconphp.com/download'); } if (!defined('TEMPLATE_PATH')) { define('TEMPLATE_PATH', $path . '/templates'); } try { $di = new \Phalcon\Di\FactoryDefault(); $di->set('view', function () use($path) { $view = new \Phalcon\Mvc\View(); $view->setViewsDir($path . '/scripts/Phalcon/Web/Tools/views/'); return $view; }); $di->set('config', $config); $di->set('url', function () use($config) { $url = new \Phalcon\Mvc\Url(); $url->setBaseUri($config->application->baseUri); return $url; }); $di->set('flash', function () { return new \Phalcon\Flash\Direct(array('error' => 'alert alert-error', 'success' => 'alert alert-success', 'notice' => 'alert alert-info')); }); $di->set('db', function () use($config) { return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name)); }); self::$_di = $di; $app = new \Phalcon\Mvc\Application(); $app->setDi($di); echo $app->handle()->getContent(); } catch (\Phalcon\Exception $e) { echo get_class($e), ': ', $e->getMessage(), "<br>"; echo nl2br($e->getTraceAsString()); } catch (\PDOException $e) { echo get_class($e), ': ', $e->getMessage(), "<br>"; echo nl2br($e->getTraceAsString()); } }
/** * @description Phalcon - Phalcon\Events\Manager */ $di->setShared(Services::EVENTS_MANAGER, new \Phalcon\Events\Manager()); /** * @description Phalcon - \Phalcon\Mvc\View\Simple */ $di->setShared(Services::VIEW, function () use($config) { $view = new Phalcon\Mvc\View\Simple(); $view->setViewsDir($config->application->viewsDir); return $view; }); /** * @description Phalcon - \Phalcon\Mvc\Router */ $di->set(Services::ROUTER, new \Phalcon\Mvc\Router()); /** * @description App - \App\Http\Response */ $di->setShared(Services::RESPONSE, new \App\Services\Response()); /** * @description Phalcon - \Phalcon\Crypt */ $di->set(Services::CRYPT, function () use($config) { $crypt = new \Phalcon\Crypt(); $crypt->setKey($config->cryptKey); return $crypt; }); /** * @description Phalcon - \Phalcon\Http\Response\Cookies */
<?php date_default_timezone_set('Europe/Moscow'); try { //Read the configuration $config = new Phalcon\Config\Adapter\Ini('../app/Config/config.ini'); //Register an autoloader $loader = new Phalcon\Loader(); $loader->registerDirs(array('../', '../' . $config->application->controllersDir, '../' . $config->application->modelsDir)); $loader->register(); //Create a DI $di = new Phalcon\Di\FactoryDefault(); //Определяем кастомные маршруты $di->set('router', function () use($di) { $router = new Phalcon\Mvc\Router(); $router->add("/login", array("controller" => "auth", "action" => "login")); $router->add("/logout", array("controller" => "auth", "action" => "logout")); return $router; }); // Коннект к базе данных создается соответственно параметрам в конфигурационном файле $di->set('db', function () use($config) { return new Phalcon\Db\Adapter\Pdo\Mysql(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "options" => [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'])); }); //Отлавливаем авторизацию $di->set('dispatcher', function () use($di) { // Получаем стандартный менеджер событий с помощью DI $eventsManager = $di->getShared('eventsManager'); // Инстанцируем плагин безопасности $security = new Core_UserCenter_Security($di); // Плагин безопасности слушает события, инициированные диспетчером $eventsManager->attach('dispatch', $security); $dispatcher = new Phalcon\Mvc\Dispatcher();