Пример #1
0
 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);
 }
Пример #2
0
 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);
 }
Пример #3
0
 /**
  * @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;
 }
Пример #4
0
 public function testShouldRegisterServicesDefinedInArray()
 {
     $di = new \Phalcon\Di\FactoryDefault();
     $fooClassStr = 'class Foo implements \\Vegas\\Di\\Injector\\SharedServiceProviderInterface {
         public function getName() {
             return "foo";
         }
         public function getProvider(\\Phalcon\\DiInterface $di) {
             return function() {
                 $o = new \\stdClass;
                 $o->foo = "bar";
                 return $o;
             };
         }
     }';
     eval($fooClassStr);
     $barClassStr = 'class Bar implements \\Vegas\\Di\\Injector\\SharedServiceProviderInterface {
         public function getName() {
             return "bar";
         }
         public function getProvider(\\Phalcon\\DiInterface $di) {
             return function() {
                 $o = new \\stdClass;
                 $o->bar = "foo";
                 return $o;
             };
         }
     }';
     eval($barClassStr);
     $injector = new Injector($di);
     $injector->inject(['Foo', 'Bar']);
     $this->assertTrue($di->has('foo'));
     $this->assertNotNull($di->get('foo'));
     $this->assertNotNull($di->get('bar'));
     $this->assertEquals("foo", $di->get('bar')->bar);
     $this->assertEquals("bar", $di->get('foo')->foo);
 }
Пример #5
0
 public function testCrash()
 {
     $di = new Phalcon\Di\FactoryDefault();
     $bag = $di->get('sessionBag', array('dummy'));
     $this->assertTrue(true);
 }
Пример #6
0
<?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);
Пример #7
0
//includes
include 'lib/XmlStringStreamer.php';
include 'lib/XmlStringStreamer/ParserInterface.php';
include 'lib/XmlStringStreamer/StreamInterface.php';
include 'lib/XmlStringStreamer/Parser/StringWalker.php';
include 'lib/XmlStringStreamer/Parser/UniqueNode.php';
include 'lib/XmlStringStreamer/Stream/File.php';
include 'lib/XmlStringStreamer/Stream/Stdin.php';
include 'lib/xml2json.php';
require 'lib/mailer/swift_required.php';
require 'lib/Utils.php';
//Config
include "config.php";
//Bootstrap app
$di = new \Phalcon\Di\FactoryDefault();
$app = new \Phalcon\Mvc\Micro($di);
//Set logger
$logger = new \Phalcon\Logger\Adapter\File(LOG_FILE);
//Set error handler
set_error_handler(function ($errno, $errstr, $errfile, $errline) use($app, $logger) {
    $logger->error("{$errno}, {$errstr}, {$errfile}, {$errline}");
});
//Set falar error logging
register_shutdown_function(function () use($logger) {
    $error = error_get_last();
    if (isset($error['type'])) {
        $logger->error("{$error['type']} {$error['message']} {$error['file']} {$error['line']}");
    }
});
//Set mailer
Пример #8
0
    $loader=new \Phalcon\Loader();
    $loader->registerDirs([
        '../app/controllers',
        '../app/models',
        '../app/config'
    ]);

    $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'
Пример #9
0
<?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) {
Пример #10
0
<?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();
}
Пример #11
0
<?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');
Пример #12
0
 /**
  * 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());
     }
 }
<?php

use App\Constants\Services;
$di = new Phalcon\Di\FactoryDefault();
/**
 * @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;
Пример #14
0
<?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);