Beispiel #1
0
<?php

use Phalcon\DI\FactoryDefault, Phalcon\Mvc\View\Simple as View, Phalcon\Mvc\Url as UrlResolver, Phalcon\Mvc\View\Engine\Volt as VoltEngine;
/**
 * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
 */
$di = new FactoryDefault();
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('url', function () use($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);
    return $url;
}, true);
/**
 * Setting up the view component
 */
$di->set('view', function () use($config) {
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
    $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
        $volt = new VoltEngine($view, $di);
        $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_'));
        return $volt;
    }));
    return $view;
}, true);
<?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);
Beispiel #3
0
 public function testRenderWithRegisteredEngine()
 {
     $view = new View();
     $view->setDI(new Di());
     $view->setViewsDir('unit-tests/views/');
     $view->setParamToView('name', 'FooBar');
     $view->registerEngines(array('.mhtml' => 'Phalcon\\Mvc\\View\\Engine\\Volt'));
     $this->assertEquals('Hello FooBar', $view->render('test4/index'));
 }
 */
$container->set('url', function () use($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);
    return $url;
}, true);
/**
 * The Views component
 *
 */
$container->set('view', function () use($config) {
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
    $view->registerEngines(array('.volt' => function ($view, $container) use($config) {
        $volt = new VoltEngine($view, $container);
        $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeperator' => '_'));
        return $volt;
    }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
    return $view;
}, true);
/**
 * The database component
 *
 */
$container->set('db', function () use($config) {
    return new DbAdapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname));
});
/**
 * Models metadata
 *
 */
Beispiel #5
0
 /**
  * Tests the Simple::getRegisteredEngines
  *
  * @author Kamil Skowron <*****@*****.**>
  * @since  2014-05-28
  */
 public function testGetRegisteredEngines()
 {
     $this->specify('Unable to get all registered engines', function () {
         $expected = ['.mhtml' => MustacheEngine::class, '.phtml' => PhpEngine::class, '.twig' => TwigEngine::class, '.volt' => VoltEngine::class];
         $view = new Simple();
         $view->setViewsDir(PATH_DATA . 'views' . DIRECTORY_SEPARATOR);
         $view->registerEngines($expected);
         expect($view->getRegisteredEngines())->equals($expected);
     });
 }
Beispiel #6
0
 */
$di->set('url', function () use($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);
    return $url;
}, true);
/**
 * Setting up the view component
 */
$di->set('view', function () use($config) {
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
    $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
        $volt = new VoltEngine($view, $di);
        if (!isset($_SERVER['CLEARDB_DATABASE_URL'])) {
            $volt->setOptions(array('compiledPath' => $config->application->cacheDir, 'compiledSeparator' => '_'));
        }
        return $volt;
    }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
    return $view;
}, true);
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config) {
    return new DbAdapter(array('host' => $config->database->host, 'username' => $config->database->username, 'password' => $config->database->password, 'dbname' => $config->database->dbname));
});
/**
 * If the configuration specify the use of metadata adapter use it or use memory otherwise
 */
$di->set('modelsMetadata', function () {
Beispiel #7
0
 $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
  */
 $di->set('assets', function () {
     $assetManager = new AssetManager();
     return $assetManager;
 }, true);
Beispiel #8
0
 public function run(DiInterface $diContainer, array $options = [])
 {
     $memoryUsage = memory_get_usage();
     $currentTime = microtime(true);
     $this->diContainer = $diContainer;
     /**
      * The app path
      */
     if (!defined('K_PATH')) {
         define('K_PATH', dirname(dirname(dirname(__FILE__))));
     }
     /**
      * We will need the Utils class
      */
     require_once K_PATH . '/library/Kitsune/Utils.php';
     /**
      * Utils class
      */
     $utils = new Utils();
     $this->diContainer->set('utils', $utils, true);
     /**
      * Check if this is a CLI app or not
      */
     $cli = $utils->fetch($options, 'cli', false);
     if (!defined('K_CLI')) {
         define('K_CLI', $cli);
     }
     $tests = $utils->fetch($options, 'tests', false);
     if (!defined('K_TESTS')) {
         define('K_TESTS', $tests);
     }
     /**********************************************************************
      * CONFIG
      **********************************************************************/
     /**
      * The configuration is split into two different files. The first one
      * is the base configuration. The second one is machine/installation
      * specific.
      */
     if (!file_exists(K_PATH . '/var/config/base.php')) {
         throw new \Exception('Base configuration files are missing');
     }
     if (!file_exists(K_PATH . '/var/config/config.php')) {
         throw new \Exception('Configuration files are missing');
     }
     /**
      * Get the config files and merge them
      */
     $base = (require K_PATH . '/var/config/base.php');
     $specific = (require K_PATH . '/var/config/config.php');
     $combined = array_replace_recursive($base, $specific);
     $config = new Config($combined);
     $this->diContainer->set('config', $config, true);
     /**
      * Check if we are in debug/dev mode
      */
     if (!defined('K_DEBUG')) {
         $debugMode = boolval($utils->fetch($config, 'debugMode', false));
         define('K_DEBUG', $debugMode);
     }
     /**
      * Access to the debug/dev helper functions
      */
     if (K_DEBUG) {
         require_once K_PATH . '/library/Kitsune/Debug.php';
     }
     /**********************************************************************
      * LOADER
      **********************************************************************/
     /**
      * We're a registering a set of directories taken from the
      * configuration file
      */
     $loader = new Loader();
     $loader->registerNamespaces($config->namespaces->toArray());
     $loader->register();
     require K_PATH . '/vendor/autoload.php';
     /**********************************************************************
      * LOGGER
      **********************************************************************/
     /**
      * The essential logging service
      */
     $format = '[%date%][%type%] %message%';
     $name = K_PATH . '/var/log/' . date('Y-m-d') . '-kitsune.log';
     $logger = new LoggerFile($name);
     $formatter = new LoggerFormatter($format);
     $logger->setFormatter($formatter);
     $this->diContainer->set('logger', $logger, true);
     /**********************************************************************
      * ERROR HANDLING
      **********************************************************************/
     ini_set('display_errors', boolval(K_DEBUG));
     error_reporting(E_ALL);
     set_error_handler(function ($exception) use($logger) {
         if ($exception instanceof \Exception) {
             $logger->error($exception->__toString());
         } else {
             $logger->error(json_encode(debug_backtrace()));
         }
     });
     set_exception_handler(function (\Exception $exception) use($logger) {
         $logger->error($exception->getMessage());
     });
     register_shutdown_function(function () use($logger, $utils, $memoryUsage, $currentTime) {
         $memoryUsed = memory_get_usage() - $memoryUsage;
         $executionTime = microtime(true) - $currentTime;
         if (K_DEBUG) {
             $logger->info(sprintf('Shutdown completed [%s]s - [%s]', round($executionTime, 3), $utils->bytesToHuman($memoryUsed)));
         }
     });
     $timezone = $config->get('app_timezone', 'US/Eastern');
     date_default_timezone_set($timezone);
     /**********************************************************************
      * ROUTES
      **********************************************************************/
     if (false === K_CLI) {
         $router = new Router(false);
         $router->removeExtraSlashes(true);
         $routes = $config->routes->toArray();
         foreach ($routes as $pattern => $options) {
             $router->add($pattern, $options);
         }
         $this->diContainer->set('router', $router, true);
     }
     /**********************************************************************
      * DISPATCHER
      **********************************************************************/
     if (false === K_CLI) {
         /**
          * We register the events manager
          */
         $eventsManager = new EventsManager();
         /**
          * Handle exceptions and not-found exceptions using NotFoundPlugin
          */
         $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin());
         $dispatcher = new Dispatcher();
         $dispatcher->setEventsManager($eventsManager);
         $dispatcher->setDefaultNamespace('Kitsune\\Controllers');
     } else {
         $dispatcher = new PhCliDispatcher();
         $dispatcher->setDefaultNamespace('Kitsune\\Cli\\Tasks');
     }
     $this->diContainer->set('dispatcher', $dispatcher);
     /**********************************************************************
      * URL
      **********************************************************************/
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $url = new UrlProvider();
     $url->setBaseUri($config->baseUri);
     $this->diContainer->set('url', $url);
     /**********************************************************************
      * VIEW
      **********************************************************************/
     $view = new View();
     $view->setViewsDir(K_PATH . '/app/views/');
     $view->registerEngines([".volt" => function ($view) {
         return $this->setVoltOptions($view);
     }]);
     $this->diContainer->set('view', $view);
     /**********************************************************************
      * VIEW SIMPLE
      **********************************************************************/
     $viewSimple = new ViewSimple();
     $viewSimple->setViewsDir(K_PATH . '/app/views/');
     $viewSimple->registerEngines([".volt" => function ($view) {
         return $this->setVoltOptions($view);
     }]);
     $this->diContainer->set('viewSimple', $viewSimple);
     /**********************************************************************
      * CACHE
      **********************************************************************/
     $frontConfig = $config->cache_data->front->toArray();
     $backConfig = $config->cache_data->back->toArray();
     $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter'];
     $frontCache = new $class($frontConfig['params']);
     $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter'];
     $cache = new $class($frontCache, $backConfig['params']);
     $this->diContainer->set('cache', $cache, true);
     /**********************************************************************
      * POSTS FINDER
      **********************************************************************/
     $this->diContainer->set('finder', new PostFinder(), true);
     /**********************************************************************
      * DISPATCH 17.5s
      **********************************************************************/
     if (K_CLI) {
         return new PhCliConsole($this->diContainer);
     } else {
         $application = new Application($this->diContainer);
         if (K_TESTS) {
             return $application;
         } else {
             return $application->handle()->getContent();
         }
     }
 }
Beispiel #9
0
<?php

use Phalcon\DI\FactoryDefault, Phalcon\Assets\Manager as AssetsManager, Phalcon\Mvc\Collection\Manager as CollectionManager, Phalcon\Mvc\View\Simple as View, Phalcon\Mvc\View\Engine\Volt, Phalcon\Mvc\Url as UrlResolver, Phalcon\Flash\Session as Flash, Phalcon\Flash\Direct as FlashDirect, Phalcon\Session\Adapter\Files as Session;
$di = new FactoryDefault();
//View service
$di['view'] = function () {
    $view = new View();
    $view->setViewsDir(APP_PATH . '/views/');
    $view->registerEngines(array('.volt' => function ($view, $di) {
        $volt = new Volt($view, $di);
        $volt->setOptions(array('compiledPath' => APP_PATH . '/cache/volt/', 'compiledSeparator' => '_'));
        return $volt;
    }));
    return $view;
};
$di['url'] = function () {
    $url = new UrlResolver();
    $url->setBaseUri('/dasshy/');
    return $url;
};
$di['assets'] = function () {
    $assets = new AssetsManager();
    $assets->addJs('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', false)->addJs('//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js', false);
    return $assets;
};
/**
 * Flash service with custom CSS classes
 */
$di['flash'] = function () {
    return new Flash(array('error' => 'alert alert-error', 'success' => 'alert alert-success', 'notice' => 'alert alert-info'));
};
Beispiel #10
0
 public function testGetRegisteredEngines()
 {
     $expected = array('.mhtml' => 'My_Mustache_Engine', '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php', '.twig' => 'My_Twig_Engine', '.volt' => 'Phalcon\\Mvc\\View\\Engine\\Volt');
     $di = new Phalcon\DI();
     $view = new Phalcon\Mvc\View\Simple();
     $view->setDI($di);
     $view->setViewsDir('unit-tests/views/');
     $view->registerEngines($expected);
     $this->assertEquals($expected, $view->getRegisteredEngines());
 }
Beispiel #11
0
    $base = 'alert alert-';
    return new Flash(array('error' => $base . 'danger', 'success' => $base . 'success', 'notice' => $base . 'info', 'warning' => $base . 'warning'));
});
$di->setShared('session', function () use($config) {
    $conn = new DbAdapter($config->database->toArray());
    $session = new Database(array('db' => $conn, 'table' => 'session_data'));
    $session->start();
    return $session;
});
/**
 * Sets the view component
 */
$di->setShared('view', function () use($config) {
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
    $view->registerEngines(array(".volt" => 'Phalcon\\Mvc\\View\\Engine\\Volt', ".phtml" => 'Phalcon\\Mvc\\View\\Engine\\Php'));
    return $view;
});
/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->set('url', function () use($config) {
    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);
    return $url;
});
/**
 * Database connection is created based in the parameters defined in the configuration file
 */
$di->set('db', function () use($config) {
    return new DbAdapter($config->database->toArray());