Advertisement
vansanblch

Untitled

Jan 13th, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.10 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Homex;
  4.  
  5. use Phalcon\Mvc\Application as PhalconApplication;
  6.  
  7. use Phalcon\DI;
  8. use Phalcon\Events\Manager as EventsManager;
  9. use Phalcon\Config\Adapter\Ini as ConfigAdapter;
  10. use Phalcon\Session\Adapter\Files as SessionFiles;
  11. use Phalcon\Mvc\Model\Manager as ModelsManager;
  12. use Phalcon\Flash\Direct as FlashDirect;
  13. use Phalcon\Flash\Session as FlashSession;
  14. use Phalcon\Loader;
  15.  
  16. class Application extends PhalconApplication
  17. {
  18.     const SYSTEM_CONFIG_PATH = '/config/application.php';
  19.  
  20.     const MODE_PRODUCTION = 'prod';
  21.     const MODE_TESTING    = 'test';
  22.     const MODE_DEVELOPING = 'dev';
  23.  
  24.     const DEFAULT_MODE = 'dev';
  25.  
  26.     /**
  27.      * Set application mode and error reporting level.
  28.      */
  29.     public function __construct()
  30.     {
  31.         $di = new Di\FactoryDefault();
  32.  
  33.         parent::__construct($di);
  34.     }
  35.  
  36.     public function run($mode = null)
  37.     {
  38.         $di = $this->getDI();
  39.  
  40.         $eventsManager = new EventsManager();
  41.  
  42.         $this->setEventsManager($eventsManager);
  43.         $di->setShared('eventsManager', $eventsManager);
  44.  
  45.         $defaultMode = self::DEFAULT_MODE;
  46.         $di['mode'] = function () use ($mode, $defaultMode) {
  47.             return $mode ? $mode : $defaultMode;
  48.         };
  49.  
  50.         $this->initConfig($di);
  51.  
  52.         $this->initLoader($di);
  53.         $this->initRouter($di);
  54.         $this->initSession($di);
  55.         $this->initFlash($di);
  56.         $this->initDatabase($di);
  57.  
  58.         $di->set('volt', function ($view, $di) {
  59.             $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
  60.  
  61.             $volt->setOptions([
  62.                 'compiledPath' => ROOT_PATH.'/cache/',
  63.             ]);
  64.  
  65.             return $volt;
  66.         }, true);
  67.  
  68.         $di->setShared('app', $this);
  69.  
  70.         $this->debug();
  71.  
  72.         $this->handle()->send();
  73.     }
  74.  
  75.     protected function debug()
  76.     {
  77.         $di = $this->getDI();
  78.         $config = $di['config'];
  79.  
  80.         if ((self::MODE_DEVELOPING === $di['mode']) || $config->application->debug) {
  81.             $debug = new \Phalcon\Debug();
  82.             $debug->listen();
  83.         }
  84.     }
  85.  
  86.     protected function initLoader($di)
  87.     {
  88.         $config = $di['config'];
  89.  
  90.         $modules = array_merge([
  91.         ], $config->modules->toArray());
  92.  
  93.         $modules = array_filter($modules);
  94.         $di->set('modules', function () use ($modules) {
  95.             return $modules;
  96.         });
  97.  
  98.         $modulesNamespaces = [
  99.             'Homex' => ROOT_PATH.'/app/',
  100.             'Core' => ROOT_PATH.'/app/Core/',
  101.         ];
  102.  
  103.         $bootstraps = [];
  104.  
  105.         foreach ($di['modules'] as $module => $enabled) {
  106.             $moduleName = ucfirst($module);
  107.             $modulePath = $config->application->modulesDir.$moduleName.'/Module.php';
  108.  
  109.             if (file_exists($modulePath)) {
  110.                 $modulesNamespaces[ $moduleName ] = $config->application->modulesDir.$moduleName.'/';
  111.                 $bootstraps[ $module ] = [
  112.                     'className' => $moduleName.'\Module',
  113.                     'path'      => $modulePath,
  114.                 ];
  115.             }
  116.         }
  117.  
  118.         $loader = new Loader();
  119.         $loader->registerNamespaces($modulesNamespaces);
  120.  
  121.         $loader->register();
  122.  
  123.         $this->registerModules($bootstraps);
  124.  
  125.         $di->set('loader', $loader);
  126.  
  127.         return $loader;
  128.     }
  129.  
  130.     protected function initRouter($di)
  131.     {
  132.         $modules = $di['modules'];
  133.         $config  = $di['config'];
  134.  
  135.         $router = new \Phalcon\Mvc\Router\Annotations(false);
  136.         $router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_SERVER_REQUEST_URI);
  137.  
  138.         $router->add('/:module/:controller/:action', [
  139.             'module'     => 1,
  140.             'controller' => 2,
  141.             'action'     => 3,
  142.         ]);
  143.  
  144.         $router->notFound([
  145.             'namespace' => 'Homex\Controller',
  146.             'controller' => 'Errors',
  147.             'action'     => 'show404'
  148.         ]);
  149.  
  150.         // foreach module attach annotated and grouped routes
  151.         foreach ($modules as $module => $moduleData) {
  152.             $moduleName = ucfirst($module);
  153.             $moduleDir = $config->application->modulesDir.$moduleName;
  154.  
  155.             if (!is_dir($moduleDir)) {
  156.                 continue;
  157.             }
  158.  
  159.             $files = scandir($moduleDir.'/Controller');
  160.             foreach ($files as $file) {
  161.                 if (!strpos($file, '.') || !strpos($file, 'Controller.php')) {
  162.                     continue;
  163.                 }
  164.  
  165.                 $controller = sprintf(
  166.                     '%s\\Controller\\%s',
  167.                     $moduleName,
  168.                     str_replace('Controller.php', '', $file)
  169.                 );
  170.                 $router->addModuleResource($module, $controller);
  171.             }
  172.  
  173.             $moduleRoute = '\\'.$moduleName.'\Routes';
  174.             if (class_exists($moduleRoute)) {
  175.                 $router->mount(new $moduleRoute());
  176.             }
  177.         }
  178.  
  179.         $di->set('router', $router);
  180.  
  181.         return $router;
  182.     }
  183.  
  184.     public function initConfig($di)
  185.     {
  186.         $config = include_once(ROOT_PATH . self::SYSTEM_CONFIG_PATH);
  187.  
  188.         if (file_exists($config->application->configDir.'settings.ini')) {
  189.             $config->merge(
  190.                 new ConfigAdapter($config->application->configDir.'settings.ini')
  191.             );
  192.         }
  193.  
  194.         $mode = $di['mode'];
  195.  
  196.         if ($mode !== self::MODE_PRODUCTION) {
  197.             $modeConfig = $config->application->configDir.'/settings.'.$mode.'.ini';
  198.             if (file_exists($modeConfig)) {
  199.                 $config->merge(
  200.                     new ConfigAdapter($modeConfig)
  201.                 );
  202.             }
  203.         }
  204.  
  205.         $di->setShared('config', $config);
  206.     }
  207.  
  208.     protected function initSession($di)
  209.     {
  210.  
  211.         $di->set('session', function () {
  212.             $session = new SessionFiles();
  213.             $session->start();
  214.             return $session;
  215.         }, true);
  216.     }
  217.  
  218.     /**
  219.      * Init flash messages.
  220.      *
  221.      * @param DI $di Dependency Injection.
  222.      *
  223.      * @return void
  224.      */
  225.     protected function initFlash($di)
  226.     {
  227.         $di->set('flash', function () {
  228.             $flash = new FlashDirect([
  229.                 'error' => 'alert alert-error',
  230.                 'success' => 'alert alert-success',
  231.                 'notice' => 'alert alert-info',
  232.             ]);
  233.  
  234.             return $flash;
  235.         });
  236.  
  237.         $di->set('flashSession', function () {
  238.             $flash = new FlashSession([
  239.                 'error' => 'alert alert-error',
  240.                 'success' => 'alert alert-success',
  241.                 'notice' => 'alert alert-info',
  242.             ]);
  243.  
  244.             return $flash;
  245.         });
  246.     }
  247.  
  248.     /**
  249.      * Init database.
  250.      *
  251.      * @param DI            $di            Dependency Injection.
  252.      *
  253.      * @return Pdo
  254.      */
  255.     protected function initDatabase($di)
  256.     {
  257.         $config = $di['config'];
  258.  
  259.         $adapter = '\Phalcon\Db\Adapter\Pdo\\' . $config->database->adapter;
  260.  
  261.         /** @var Pdo $connection */
  262.         $connection = new $adapter([
  263.             'host'     => $config->database->host,
  264.             'username' => $config->database->username,
  265.             'password' => $config->database->password,
  266.             'dbname'   => $config->database->dbname,
  267.             'options' => [
  268.                 \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
  269.                 \PDO::ATTR_CASE => \PDO::CASE_LOWER,
  270.             ]
  271.         ]);
  272.  
  273.         $di->set('db', $connection);
  274.  
  275.         $di->set('modelsManager', function () {
  276.             $modelsManager = new ModelsManager();
  277.  
  278.             return $modelsManager;
  279.         }, true);
  280.  
  281.         $di->set('modelsMetadata', function () use ($config) {
  282.             if (isset($config->metadata)) {
  283.                 $metaDataConfig = $config->metadata;
  284.                 $metadataAdapter = '\Phalcon\Mvc\Model\Metadata\\' . $metaDataConfig->adapter;
  285.                 $metaData = new $metadataAdapter($config->metadata->toArray());
  286.             } else {
  287.                 $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
  288.             }
  289.  
  290.             return $metaData;
  291.         }, true);
  292.  
  293.         return $connection;
  294.     }
  295.  
  296.     private function testRoutes($router)
  297.     {
  298.         $testRoutes = array(
  299.             '/',
  300.             '/crm',
  301.             '/crm/',
  302.             '/crm/orders',
  303.             '/crm/orders/',
  304.             '/crm/orders/detail',
  305.             '/crm/orders/detail?id=2',
  306.         );
  307.  
  308.         //Testing each route
  309.         foreach ($testRoutes as $testRoute) {
  310.  
  311.             //Handle the route
  312.             $router->handle($testRoute);
  313.  
  314.             echo 'Testing ', $testRoute, '<br>';
  315.  
  316.             //Check if some route was matched
  317.             if ($router->wasMatched()) {
  318.                 echo 'Module: ', $router->getModuleName(), '<br>';
  319.                 echo 'Controller: ', $router->getControllerName(), '<br>';
  320.                 echo 'Action: ', $router->getActionName(), '<br>';
  321.             } else {
  322.                 echo 'The route wasn\'t matched by any route<br>';
  323.             }
  324.             echo '<br>';
  325.  
  326.         }
  327.     }
  328. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement