Esempio n. 1
0
 public function get($routeName, $routeParams = array())
 {
     $url = $this->di->get('url');
     $options = array('for' => $routeName);
     $options = array_merge($options, $routeParams);
     return $url->get($options);
 }
Esempio n. 2
0
File: Di.php Progetto: vegas-cmf/mvc
 public function get($alias, $parameters = null)
 {
     $result = parent::get($alias, $parameters);
     $injector = new \Vegas\Mvc\Di\Manager();
     $injector->setDI($this);
     $injector->inject($result);
     return $result;
 }
Esempio n. 3
0
 /**
  * Inject of Phalcon dependency container
  *
  * @param \Phalcon\DI\FactoryDefault $dependency
  * @throws BaseException
  */
 public function __construct(\Phalcon\DI\FactoryDefault $dependency)
 {
     if ($dependency->has('config') === true) {
         $this->config = $dependency->get('config')->sms->toArray();
     } else {
         throw new BaseException('SMS', 'Please setup your configuration to $dependency', 500);
     }
 }
Esempio n. 4
0
 public function get($name, $parameters = [])
 {
     if ($this->router == null) {
         //$this->router = $this->getShared ( 'router' );
         $this->router = parent::get('router');
         $this->_init = true;
     }
     if ($this->_init) {
         $this->checkPermission($name);
     }
     return parent::get($name, $parameters);
 }
Esempio n. 5
0
 public function setUp()
 {
     $this->task = new ImportDmmTask();
     $di = new Di\FactoryDefault();
     $db = function () {
         return new Mysql(array("host" => $GLOBALS['db_host'], "username" => $GLOBALS['db_username'], "password" => $GLOBALS['db_password'], "dbname" => 'yinxing'));
     };
     $di->set('dbSlave', $db);
     $di->set('dbMaster', $db);
     $di->set('moduleManager', function () {
         return new ModuleManager();
     });
     /** @var Mysql $mysql */
     $mysql = $di->get('dbMaster');
     $mysql->query(file_get_contents(__DIR__ . '/../../sql/evamovie_2015-10-20.sql'));
 }
Esempio n. 6
0
 /**
  * @param \Phalcon\DI\FactoryDefault     $di
  */
 protected function registerViewService($di)
 {
     /**
      * Setting up the view component
      */
     $di['view'] = function () use($di) {
         /*
          * Obtengo el nombre del modulo para poder obner el archivo de configuracion
          */
         $module = $this->name;
         $this->layout_dir = '../../../../public/layouts/' . $di->get('modules')->{$module}->layout . '/';
         $view = new View();
         $view->setViewsDir($this->path . $this->view_dir);
         $view->setLayoutsDir($this->layout_dir);
         $view->setTemplateAfter($this->template);
         $view->setVar('project-setting', $di->get('config')->project->toArray());
         /*
          * Registra Constantes de Modulo
          */
         $view->setVar('module-setting', $di->get('modules')->{$module}->toArray());
         // Set the engine
         $view->registerEngines(array(".mustache" => function ($view, DI $di) {
             $module = $this->name;
             $partial_url = '../public/layouts/' . $di->get('modules')->{$module}->layout . '/partials';
             $partial_loader = new Mustache_Loader_FilesystemLoader($partial_url);
             $config = $di->get('config')->cache->frontend;
             if ($config->active == 0) {
                 $options = array('partials_loader' => $partial_loader);
             } else {
                 $options = array('cache' => '/var/www/var/cache/elephant', 'cache_file_mode' => $config->mode, 'partials_loader' => $partial_loader, 'strict_callables' => $config->callables);
             }
             $mustache = new Mustache($view, $di, $options);
             return $mustache;
         }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
         return $view;
     };
 }
<?php

use Phalcon\Mvc\View\Simple as SimpleView;
use Phalcon\Di\FactoryDefault;
use Phalcon\Config\Adapter\Php as PhpConfig;
$di = new FactoryDefault();
$di->set('config', function () {
    $config = new PhpConfig(__DIR__ . '/app.php');
    if (is_readable(__DIR__ . '/app.development.php') && getenv('APPLICATION_ENV') == 'development') {
        $development = new PhpConfig(__DIR__ . '/app.development.php');
        $config->merge($development);
    }
    return $config;
}, true);
$di->set('view', function () use($di) {
    $config = $di->get('config')['view'];
    $view = new SimpleView();
    $view->setViewsDir($config['dir']);
    $view->setVar('appConfig', $di->get('config')['app']);
    $view->setVar('flashSession', $di->get('flashSession'));
    $engine = new $config['engine']($view);
    $engine->setOptions([$config['options']]);
    $view->registerEngines([$config['prefix'] => $engine]);
    return $view;
}, true);
$di->set('connection', function () use($di) {
    $config = $di->get('config')['database'];
    $adapter = new $config->adapter(["host" => $config->host, "username" => $config->username, "password" => $config->password, "dbname" => $config->db]);
    return $adapter;
}, true);
Esempio n. 8
0
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->set('modelsMetadata', function () {
    return new MetaDataAdapter();
});
/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
$language = $di->get("session")->get("language");
//Set default language
if (!$language) {
    $language = 'es';
}
$di->set('translate', function () use($config, $language) {
    // Ask browser what is the best language
    $request = new Request();
    //echo "language". $dispatcher->getParam('language');
    $translation = Translation::findBylanguagecode($language)->toArray();
    $messages = array();
    foreach ($translation as $item) {
        $messages[$item['translatekey']] = $item['value'];
    }
    //$language = $dispatcher->getParam('language');
    //echo "lenguage".$language."<br>";
Esempio n. 9
0
    return $url;
});
$di->setShared('voltService', function ($view, $di) use($config) {
    $volt = new Volt($view, $di);
    $voltOptions = !empty($config->volt) ? $config->volt->toArray() : [];
    $volt->setOptions(array_merge(['compiledPath' => APPLICATION_PATH . '/cache/views/volt/', 'compiledSeparator' => '-'], $voltOptions));
    $compiler = $volt->getCompiler();
    $compiler->addFilter('url_decode', 'urldecode')->addFilter('rawurlencode', 'rawurlencode')->addFilter('round', 'round')->addFilter('count', 'count')->addFunction('number_format', 'number_format')->addFunction('array_slice', 'array_slice')->addFunction('strpos', 'strpos');
    return $volt;
});
$di->setShared('view', function () use($config, $di) {
    $view = new \Phalcon\Mvc\View();
    //WARNING: DO NOT TOUCH EVENTS PRIORITY!!!
    /** @var \Phalcon\Events\Manager $evManager */
    $evManager = $di->getShared('eventsManager');
    $evManager->enablePriorities(true);
    $evManager->attach('view', $di->get('contextPlugin'), 0);
    $view->setViewsDir($config->application->viewsDir)->setLayout('core')->registerEngines(['.volt' => 'voltService'])->setEventsManager($evManager);
    return $view;
});
$di->set('contextPlugin', ['className' => '\\Plugin\\Context', 'calls' => [['method' => 'setRequest', 'arguments' => [['type' => 'service', 'name' => 'request']]], ['method' => 'setResponse', 'arguments' => [['type' => 'service', 'name' => 'response']]]]]);
$di->setShared('cookies', function () {
    $cookies = new Cookies();
    $cookies->useEncryption(false);
    return $cookies;
});
$di['vk'] = function () use($config) {
    $schema = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://';
    return new \OAuth\Services\Vkontakte($schema . $_SERVER['HTTP_HOST'] . ($config->vk->callback ?: ''), ['client_id' => $config->vk->id, 'client_secret' => $config->vk->secret]);
};
return $di;
Esempio n. 10
0
/**
 * Custom mail component
 */
$di->set('acl', function () {
    return new Acl();
});
/**
 * Set up the security service
 */
$di->set('security', function () {
    $security = new Security();
    //Set the password hashing factor to 12 rounds
    $security->setWorkFactor(12);
    return $security;
}, true);
/**
 * Set the encryption service
 * Key: 7}T/~"4%[GW*7O-)!"nU
 */
$di->setShared('crypt', function () {
    $crypt = new \Phalcon\Crypt();
    $crypt->setMode(MCRYPT_MODE_CFB);
    $crypt->setKey('7}T/~"4%[GW*7O-)!"nU');
    return $crypt;
});
/**
 * Set global access to config, excluding db settings
 */
$di->set('config', $config);
$di->get('auth');
Esempio n. 11
0
if (file_exists(__DIR__ . '/config.global.php')) {
    $overrideConfig = (include __DIR__ . '/config.global.php');
    $config->merge($overrideConfig);
}
//It crreated when save in admin dashboard
if (file_exists(ROOT_DIR . 'content/options/options.php')) {
    $overrideConfig = new AdapterPhp(ROOT_DIR . 'content/options/options.php');
    $config->merge($overrideConfig);
}
if (file_exists(__DIR__ . '/config.' . APPLICATION_ENV . '.php')) {
    $overrideConfig = (include __DIR__ . '/config.' . APPLICATION_ENV . '.php');
    $config->merge($overrideConfig);
}
$di->set('config', $config, true);
// setup timezone
date_default_timezone_set($di->get('config')->application->timezone ?: 'UTC');
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('url', function () use($di) {
    $url = new UrlResolver();
    $config = $di->get('config');
    if (APPLICATION_ENV == 'production') {
        $url->setStaticBaseUri($config->application->production->staticBaseUri);
    } else {
        $url->setStaticBaseUri($config->application->development->staticBaseUri);
    }
    $url->setBaseUri($config->application->baseUri);
    return $url;
});
/**
Esempio n. 12
0
 /**
  * Obtains a service from the DI
  *
  * @param string $serviceName
  * @return object
  */
 public function getSharedService($serviceName)
 {
     $dependencyInjector = null;
     $dependencyInjector = $this->_dependencyInjector;
     if (!is_object($dependencyInjector)) {
         $dependencyInjector = new FactoryDefault();
         $this->_dependencyInjector = $dependencyInjector;
     }
     return $dependencyInjector->get($serviceName);
 }
Esempio n. 13
0
//     $url->setBaseUri('/');
//     return $url;
// });
/**
 * This service controls the initialization of models, keeping record of relations
 * between the different models of the application.
 */
$di->set('collectionManager', function () {
    return new Manager();
});
$di->set('modelsManager', function () {
    return new ModelsManager();
});
// Database connection is created based in the parameters defined in the configuration file
$di->set('db', function () use($di) {
    return new Mysql(['host' => $di->get('config')->database->mysql->host, 'username' => $di->get('config')->database->mysql->username, 'password' => $di->get('config')->database->mysql->password, 'dbname' => $di->get('config')->database->mysql->dbname, 'options' => [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $di->get('config')->database->mysql->charset]]);
}, true);
$di->set('cookies', function () {
    $cookies = new Cookies();
    $cookies->useEncryption(false);
    return $cookies;
}, true);
$di->set('security', function () {
    $security = new Security();
    //Set the password hashing factor to 12 rounds
    $security->setWorkFactor(12);
    return $security;
}, true);
//Set the models cache service
$di->set('modelsCache', function () {
    //Cache data for one day by default
Esempio n. 14
0
        $appender->setLogLevel(Logger::ERROR);
        $logger->push($appender);
    }
    return $logger;
};
$di['db'] = function () use($di, $config) {
    Model::setup(['notNullValidations' => false]);
    $conn = new DbAdapter($config->database->toArray());
    if (isset($config->eventListeners->db)) {
        $em = $di['eventsManager'];
        foreach ($config->eventListeners->db as $listener => $options) {
            if (is_numeric($listener)) {
                $listener = $options;
                $options = null;
            }
            $em->attach('db', $di->get($listener, [$options]));
        }
        $conn->setEventsManager($em);
    }
    return $conn;
};
if (extension_loaded('apcu')) {
    $di['modelsMetadata'] = function () use($config) {
        return new MetadataApc($config->metadata->toArray());
    };
} else {
    $di['modelsMetadata'] = MetadataMemory::CLASS;
}
$di['eventsManager'] = function () use($di, $config) {
    $eventsManager = new EventsManager();
    $di['eventsManager'] = $eventsManager;
Esempio n. 15
0
}, true);
/**
 * This service controls the initialization of models, keeping record of relations
 * between the different models of the application.
 */
$di->set('collectionManager', function () {
    return new Manager();
});
// Register the flash service with custom CSS classes
$di->set('flashSession', function () {
    $flash = new Session(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info'));
    return $flash;
});
// Database connection is created based in the parameters defined in the configuration file
$di->set('db', function () use($di) {
    return new Mysql(['host' => $di->get('config')->database->host, 'username' => $di->get('config')->database->username, 'password' => $di->get('config')->database->password, 'dbname' => $di->get('config')->database->dbname, 'schema' => $di->get('config')->database->schema, 'options' => array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $di->get('config')->database->charset)]);
}, true);
$di->set('cookies', function () {
    $cookies = new Cookies();
    return $cookies;
}, true);
$di->set('crypt', function () use($di) {
    $crypt = new Crypt();
    $crypt->setKey($di->get('config')->application->cryptSalt);
    //Use your own key!
    return $crypt;
});
$di->set('security', function () {
    $security = new Security();
    //Set the password hashing factor to 12 rounds
    $security->setWorkFactor(12);
Esempio n. 16
0
 private function getCurrentRenderLevel()
 {
     return $this->di->get('view')->getCurrentRenderLevel();
 }
Esempio n. 17
0
<?php

use Phalcon\Config, Phalcon\Loader, Phalcon\DI\FactoryDefault, Phalcon\Mvc\Url as UrlProvider, Phalcon\Session\Adapter\Files, Phalcon\Dispatcher, Phalcon\Mvc\View, Phalcon\Mvc\Dispatcher as MvcDispatcher, Phalcon\Events\Manager as EventsManager, Phalcon\Mvc\Application;
// 根目录定义
define("ROOT_PATH", dirname(__DIR__) . '/');
// 开发模式 TRUE | 线上模式 FALSE
define('DEBUG', TRUE);
try {
    //Create a DI
    $di = new FactoryDefault();
    $di->set('conf', function () {
        $config = new Config(require ROOT_PATH . '/app/config/config.php');
        $config = $config->toArray();
        return $config;
    });
    $config = $di->get('conf');
    //Register an autoloader
    $loader = new Loader();
    $loader->registerDirs(array($config['application']['controller'], $config['application']['libDir'], $config['application']['modelsDir'], $config['application']['logicsDir']))->register();
    //Setup a base URI so that all generated URIs include the "tutorial" folder
    $di->set('url', function () use($config) {
        $url = new UrlProvider();
        $url->setBaseUri($config['application']['baseUri']);
        return $url;
    });
    //Start the session the first time a component requests the session service
    $di->set('session', function () {
        $session = new Files();
        $session->start();
        return $session;
    });
Esempio n. 18
0
$di->set('dispatcher', function () {
    return include "dispatcher.php";
}, true);
/*
 * 设置redis
 */
$di->set("redis", function () {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    return $redis;
}, true);
$di->set("carbon", function () {
    return new \Carbon\Carbon();
});
/*
 * 设置注册表对象
 * 在这里可以设置一些数组或者别的东西以便统一共享的
 */
$di->set('registry', function () {
    $registry = new \Phalcon\Registry();
    $registry->allTags = Tags::getTagsInfo();
    return $registry;
});
//下面合格为什么能够使用了呢?为什么上面这个不能够使用呢?比较奇怪的问题呀!
/*
 * 身份验证的结果,这里给出当前登录的用户的身份,这里没有考虑guest的角色,将来可以考虑一下
 * 权限管理的设置需要找时间看看怎么做的!
 */
$di->set('auth', function () use($di) {
    return Users::findFirst($di->get('session')->get('auth')['id']);
});
Esempio n. 19
0
$di['flash'] = function () {
    $flash = new Phalcon\Flash\Direct(['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info']);
    return $flash;
};
/**
 * Register the flash service with custom CSS classes
 */
$di['flashSession'] = function () {
    $flash = new Phalcon\Flash\Session(['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info']);
    return $flash;
};
/**
 * Logger
 */
$di->setShared('logger', function () use($di) {
    return new Phalcon\Logger\Adapter\Database('errors', array('db' => $di->get('db'), 'table' => TABLE_PREFIX . 'logs'));
});
$di['modelsCache'] = function () use($config) {
    $frontCache = new Phalcon\Cache\Frontend\Data(['lifetime' => 60, 'prefix' => HOST_HASH]);
    $cache = '';
    switch ($config->cache) {
        case 'file':
            $cache = new Phalcon\Cache\Backend\File($frontCache, ['cacheDir' => APP_URL . 'cache/model/']);
            break;
        case 'memcache':
            $cache = new Phalcon\Cache\Backend\Memcache($frontCache, ['host' => $config->memcache->host, 'port' => $config->memcache->port]);
            break;
    }
    return $cache;
};
$di['cache'] = function () use($di) {
Esempio n. 20
0
// 获取所有controller下的模块
$di->set('modules', function () use($di) {
    $cacheRedis = $di->getRedis();
    $dirRes = $cacheRedis->get('application:modules');
    $modules = json_decode($dirRes);
    if (!$modules) {
        $modules = shell_exec("ls ../app/controllers/ |grep -E '[^\\.php]\$'|tr '\n' ','");
        $modules = explode(",", $modules);
        array_pop($modules);
        $cacheRedis->set('application:modules', json_encode($modules));
    }
    return $modules;
});
//遍历注册模块
$di->set('registerModules', function () use($di) {
    $modules = $di->get('modules');
    $regModules = [];
    foreach ($modules as $key => $val) {
        $regModules[$val] = ['className' => "Modules\\{$val}\\Module", 'path' => "../app/controllers/{$val}/Module.php"];
    }
    return $regModules;
});
// 加载每个模块里的路由文件
$di->set('router', function () use($di, $config) {
    $modules = $di->get('modules');
    $router = new Router();
    $adminRouterGroup = new RouterGroup();
    // 管理类分组
    $adminRouterGroup->setPrefix($config->application->adminPrefix);
    $frontendRouterGroup = new RouterGroup();
    //前端显示类分组
Esempio n. 21
0
/**
 * Setting up the view component
 */
$di->setShared('view', function () use($config) {
    $view = new View();
    $view->disable();
    return $view;
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->setShared('modelsMetadata', function () {
    return new MetaDataAdapter();
});
$di->set('router', function () {
    require __DIR__ . '/routes.php';
    return $router;
});
$di->setShared('redis', function () use($config) {
    $redis = new Redis();
    $redis->connect($config->redis->host, $config->redis->port);
    return $redis;
});
$di->setShared('Neo4jClient', function () use($config) {
    $neo4jClient = new \Everyman\Neo4j\Client($config->neo4j->host, $config->neo4j->port);
    $neo4jClient->getTransport()->setAuth('neo4j', 'toor');
    //        die;
    return $neo4jClient;
});
$di->get('dispatcher')->setDefaultNamespace('FriendsApi\\controllers');
Esempio n. 22
0
 require VENDOR_DIR . 'autoload.php';
 $di = new DI();
 /**
  * Setting up the credentials config
  */
 $di->set('config', function () {
     return new Ini(APP_DIR . 'config/config.ini');
 }, true);
 /**
  * Setting up the view component
  */
 $di->set('view', function () {
     $view = new View();
     $view->setViewsDir(APP_DIR . 'views/');
     $view->registerEngines(array('.volt' => function ($view, $di) {
         $env = $di->get('config')->get('environment');
         /** @var ViewInterface|View $view */
         $volt = new Volt($view, $di);
         $volt->setOptions(array('compiledPath' => function ($templatePath) use($view) {
             $dir = rtrim(sys_get_temp_dir(), '/') . '/volt-cache';
             if (!is_dir($dir)) {
                 mkdir($dir);
             }
             return $dir . '/hunter-light%' . str_replace('/', '%', str_replace($view->getViewsDir(), '', $templatePath)) . '.php';
         }, 'compileAlways' => $env->realm != 'prod'));
         return $volt;
     }));
     return $view;
 }, true);
 /**
  * Setting up the asset manager
Esempio n. 23
0
use Phalcon\Http\Response\Cookies;
use Phalcon\Session\Adapter\Files;
require "../app/config/Config.php";
try {
    // Register an autoloader
    $loader = new Loader();
    $loader->registerDirs(array('../app/controllers/', '../app/models/', '../app/config/', '../app/libraries/'))->register();
    // Create a DI
    $di = new FactoryDefault();
    // return DB config
    $di->setShared('config', function () use($config) {
        return $config;
    });
    // Database
    $di->set('db', function () use($di) {
        $dbconfig = $di->get('config')->get('db')->toArray();
        $db = new DbAdapter($dbconfig);
        return $db;
    });
    // Setup the view component
    $di->set('view', function () {
        $view = new View();
        $view->setViewsDir('../app/views/');
        $view->registerEngines([".volt" => 'Phalcon\\Mvc\\View\\Engine\\Volt']);
        return $view;
    });
    // Setup a base URI so that all generated URIs include the "tutorial" folder
    $di->set('url', function () {
        $url = new UrlProvider();
        $url->setBaseUri('/bot/');
        return $url;
Esempio n. 24
0
$di->setShared('cookies', function () {
    $cookies = new Cookies();
    $cookies->useEncryption(false);
    return $cookies;
});
$di->setShared('activation', function () {
    return new ActivationComponent();
});
$di->setShared('filter', function () {
    $filter = new Filter();
    $filter->add('hash', function ($value) {
        var_dump(password_hash($value, PASSWORD_BCRYPT));
        die;
        return password_hash($value, PASSWORD_BCRYPT);
    });
    return $filter;
});
$di->setShared('translate', function () use($di) {
    $cookies = $di->get('cookies');
    $language = $cookies->has('language') ? $cookies->get('language') : 'en';
    $file = APP_DIR . '/messages/' . $language . '.php';
    //Check if we have a translation file for that lang
    if (file_exists($file)) {
        require_once $file;
    } else {
        // fallback to some default
        require_once APP_DIR . '/messages/en.php';
    }
    //Return a translation object
    return new NativeArray(["content" => $messages]);
});
Esempio n. 25
0
});
// one way to do reversable encryption
$di->setShared('paymentProcessor', function () {
    $setting = \PhalconRest\Models\Settings::findFirst(4);
    return new \PhalconRest\Libraries\Payments\StripeAdapter($setting->value);
});
/**
 * Database setup.
 */
$di->set('db', function () use($config, $di) {
    // config the event and log services
    $eventsManager = new EventsManager();
    $fileName = date("d_m_y");
    $logger = new FileLogger("/tmp/{$fileName}.log");
    // $registry = new \Phalcon\Registry();
    $registry = $di->get('registry');
    $registry->dbCount = 0;
    // Listen all the database events
    $eventsManager->attach('db', function ($event, $connection) use($logger, $registry) {
        if ($event->getType() == 'beforeQuery') {
            $count = $registry->dbCount;
            $count++;
            $registry->dbCount = $count;
            // $logger->log($connection->getSQLStatement(), Logger::INFO);
        }
    });
    $connection = new Connection($config['database']);
    // Assign the eventsManager to the db adapter instance
    $connection->setEventsManager($eventsManager);
    return $connection;
});
Esempio n. 26
0
                    $registered_modules[strtolower(basename($module_base))] = $namespace_name;
                }
            }
        }
    }
    // add routing for all controllers, using the following convention:
    // \module\controller\action\params
    // where module is mapped to the corresponding namespace
    foreach ($registered_modules as $module_name => $namespace_name) {
        $router->add("/" . $module_name . "/", array("namespace" => $namespace_name));
        $router->add("/" . $module_name . "/:controller/", array("namespace" => $namespace_name, "controller" => 1));
        $router->add("/" . $module_name . "/:controller/:action/", array("namespace" => $namespace_name, "controller" => 1, "action" => 2));
        $router->add("/" . $module_name . "/:controller/:action/:params", array("namespace" => $namespace_name, "controller" => 1, "action" => 2, "params" => 3));
    }
    $router->handle();
    return $router;
});
// exception handling
$di->get('eventsManager')->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
    switch ($exception->getCode()) {
        case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
            // send to error action on default index controller
            $dispatcher->forward(array('controller' => 'index', 'namespace' => '\\OPNsense\\Base', 'action' => 'handleError', 'params' => array('message' => 'controller ' . $dispatcher->getControllerClass() . ' not found', 'sender' => 'API')));
            return false;
        case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
            // send to error action on default index controller
            $dispatcher->forward(array('controller' => 'index', 'namespace' => '\\OPNsense\\Base', 'action' => 'handleError', 'params' => array('message' => 'action ' . $dispatcher->getActionName() . ' not found', 'sender' => 'API')));
            return false;
    }
});
$di->get('dispatcher')->setEventsManager($di->get('eventsManager'));
Esempio n. 27
0
if (file_exists(__DIR__ . '/config.' . APPLICATION_ENV . '.php')) {
    $overrideConfig = (include __DIR__ . '/config.' . APPLICATION_ENV . '.php');
    $config->merge($overrideConfig);
}
//It crreated when save in admin dashboard
if (file_exists(__DIR__ . '/options.php')) {
    $overrideConfig = new AdapterPhp(__DIR__ . '/options.php');
    $config->merge($overrideConfig);
}
if (file_exists(__DIR__ . '/config.menu.php')) {
    $overrideConfig = (include __DIR__ . '/config.menu.php');
    $config->merge($overrideConfig);
}
$di->set('config', $config, true);
// setup timezone
date_default_timezone_set($di->get('config')->application->timezone ?: 'UTC');
/**
 * Router
 */
$di->set('router', function () {
    return include ROOT_DIR . "/common/config/routes.php";
}, true);
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('url', function () use($di) {
    $url = new UrlResolver();
    $config = $di->get('config');
    $url->setBaseUri($config->application->baseUri);
    if (!$config->application->debug) {
        $url->setStaticBaseUri($config->application->production->staticBaseUri);
Esempio n. 28
0
/**
 * Include composer autoloader
 */
require APP_PATH . "/vendor/autoload.php";
try {
    /**
     * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
     */
    $di = new FactoryDefault();
    /**
     * Include the application services
     */
    require APP_PATH . "/app/config/services.php";
    /**
     * Handle the request
     */
    $application = new Application($di);
    echo $application->handle()->getContent();
} catch (Exception $e) {
    /**
     * Log the exception
     */
    $di->get('logger', ['error.log'])->error($e->getMessage());
    $di->get('logger', ['error.log'])->error($e->getTraceAsString());
    /**
     * Show an static error page
     */
    $response = new Response();
    $response->redirect('505.html');
    $response->send();
}
 /**
  * {@inherit}
  */
 public function module(FactoryDefault $di)
 {
     $di->get('dispatcher')->setDefaultNamespace('App\\Main\\Controllers');
 }
});*/
/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
/**
 * Set the dispatcher
 */
$di->set('dispatcher', function () use($di) {
    $dispatcher = new Dispatcher();
    $dispatcher->setDefaultNamespace('controllers');
    $eventsManager = $di->get('eventManager');
    // Set the event manager for dispatcher
    $dispatcher->setEventsManager($eventsManager);
    // Attach the listener
    $eventsManager->attach('dispatch', new ControllersListener($di));
    return $dispatcher;
});
/**
 * Set the timeService
 */
$di->setShared('timeService', function () use($config) {
    return new TimeService($config->timeService->toArray());
});
/**
 * Set the User Service
 */