/** * @param Slim $slim * * @return null */ public function configure(Slim $slim) { foreach ($this->hooks as $event => $hooks) { foreach ($hooks as $hook) { $slim->hook($event, $this->hookClosure($slim, $hook)); } } }
public function initCollectors(Slim $slim) { $this->addCollector(new SlimLogCollector($slim)); $this->addCollector(new SlimEnvCollector($slim)); $slim->hook('slim.after.router', function () use($slim) { $setting = $this->prepareRenderData($slim->container['settings']); $data = $this->prepareRenderData($slim->view->all()); $this->addCollector(new SlimResponseCollector($slim->response)); $this->addCollector(new ConfigCollector($setting)); $this->addCollector(new SlimViewCollector($data)); $this->addCollector(new SlimRouteCollector($slim)); }); }
public function __construct(Slim $app) { $this->app = $app; $this->singleton('slim', function () use($app) { return $app; }); $this->singleton('config', function ($app) { return new Config($app['slim']); }); $this['path'] = $app->config('path'); $service_manager = $this; $app->hook('slim.before', function () use($service_manager) { $service_manager->boot(); }, 1); }
public function __construct(Slim $app) { $this->registerAliases(); $this->app = $app; $this->singleton('slim', function () use($app) { return $app; }); $this->singleton('config', function ($app) { return new Config($app['slim']); }); $this['path'] = $app->config('path'); //Antes de iniciar slim, iniciamos los servicios. $service_manager = $this; $app->hook('slim.before', function () use($service_manager) { $service_manager->boot(); }, 1); Facade::setFacadeApplication($this); $this->registerBaseServiceProviders(); }
/** * Constructor. * * @param array $options The SameAs Lite Store for which we shall * provide RESTful interfaces. */ public function __construct(array $options = array()) { // fake $_SERVER parameters if required (eg command line invocation) \SameAsLite\Helper::initialiseServerParameters(); // set the default format of acceptable parameters // see http://docs.slimframework.com/routing/conditions/#application-wide-route-conditions \Slim\Route::setDefaultConditions(array('store' => '[a-zA-Z0-9_\\-\\.]+')); // initialise and configure Slim, using Twig template engine $mode = isset($options['mode']) ? $options['mode'] : 'production'; $this->app = new \Slim\Slim(array('mode' => $mode, 'debug' => false, 'view' => new \Slim\Views\Twig())); // configure Twig $this->app->view()->setTemplatesDirectory('assets/twig/'); $this->app->view()->parserOptions['autoescape'] = false; $this->app->view()->set('path', $this->app->request()->getRootUri()); // register 404 and custom error handlers $this->app->notFound(array(&$this, 'outputError404')); $this->app->error(array(&$this, 'outputException')); // '\SameAsLite\Exception\Exception::outputException' set_exception_handler(array(&$this, 'outputException')); // '\SameAsLite\Exception\Exception::outputException' // Hook to set the api path $this->app->hook('slim.before.dispatch', function () { // fix api pages such that if viewing a particular store // then the store name is automatically injected for you $params = $this->app->router()->getCurrentRoute()->getParams(); if (isset($params['store'])) { $apiPath = "datasets/{$params['store']}/api"; } else { $apiPath = 'api'; } $this->app->view()->set('apiPath', $apiPath); }); // save the options $this->appOptions = $options; // apply options to template foreach ($options as $k => $v) { $this->app->view->set($k, $v); } }
/** * This methods initializes the Slim object and defines a few hooks. */ public function init() { // create logger $loggerFactory = new MonologCreator\Factory($this->_applicationConfig['monolog']); $handlers = $loggerFactory->createHandlers($this->_applicationConfig['monolog']['logger']['slim']); $processors = $loggerFactory->createProcessors($this->_applicationConfig['monolog']['logger']['slim']); $logger = new SlimMonolog\Log\MonologWriter(array('handlers' => $handlers, 'processors' => $processors)); // create application $this->_app = new Slim\Slim(array('debug' => $this->_applicationConfig['debug'], 'log.writer' => $logger, 'log.enabled' => true, 'log.level' => Slim\Log::DEBUG)); // create hook handler $this->_hook = new SlimBootstrap\Hook($this->_applicationConfig, $this->_app, $this->_authentication, $this->_aclConfig); // define hooks $this->_app->hook('slim.before.router', array($this->_hook, 'requestPath')); $this->_app->hook('slim.before.router', array($this->_hook, 'cacheAndAccessHeader')); $this->_app->hook('slim.before.router', array($this->_hook, 'outputWriter')); $this->_app->hook('slim.before.dispatch', array($this->_hook, 'authentication')); $this->_app->hook('slim.after.router', array($this->_hook, 'responseStatus')); // remove token from GET params $this->_params = $this->_app->request->get(); unset($this->_params['token']); }
$app->hook('slim.before.dispatch', function () use($app, $data, $pages) { $routeName = $app->router()->getCurrentRoute()->getName(); if (isset($data['langs']['metas'][$routeName])) { $data['metas']['title'] = $data['langs']['metas'][$routeName]['title']; $data['metas']['description'] = $data['langs']['metas'][$routeName]['description']; $data['metas']['keywords'] = $data['langs']['metas'][$routeName]['keywords']; } $menu_langs = []; if ($routeName) { foreach ($data['app_langs'] as $lang) { $routeItem = new stdClass(); $routeItem->lang = $lang; $routeItem->route = '/' . $lang; if (isset($pages[$routeName])) { if ($lang == $data['default_lang']) { $routeItem->route = ''; if ($pages[$routeName][$lang]['route'] == '/') { $routeItem->route = '/'; } } if ($pages[$routeName][$lang]['route'] != '/') { $routeItem->route .= $pages[$routeName][$lang]['route']; } } $menu_langs[] = $routeItem; $routeItem = null; } } $data['menu_langs'] = $menu_langs; $app->view->appendData($data); });
$view->parserOptions = array('cache' => APP_CACHE, 'auto_reload' => true); } if (!defined('DEFAULT_PICTURE')) { define('DEFAULT_PICTURE', 'main.jpg'); } $app->hook('slim.before.dispatch', function () use($app, $conf, $lang, $app_base_url) { //let's send view parameters before dispatching $v = $app->view(); $ui = $conf->getUI(); $v->setData('app_base_url', $app_base_url); $v->setData('app_web_url', str_replace(array('/index.php', '/debug.php'), array('', ''), $app_base_url)); $v->setData('enable_right_click', $ui['enable_right_click']); $v->setData('lang', $lang); $v->setData('negate', $ui['negate']); $v->setData('contrast', $ui['contrast']); $v->setData('brightness', $ui['brightness']); $v->setData('print', $ui['print']); $v->setData('comment', $conf->getComment()); $fmts = $conf->getFormats(); $v->setData('thumb_format', $fmts['thumb']); $remote_infos = $conf->getRemoteInfos(); if ($remote_infos !== false) { $v->setData('remote_method', $remote_infos['method']); $v->setData('remote_uri', $remote_infos['uri']); } }); //set default conditions Route::setDefaultConditions(array('image' => '.+\\.[a-zA-Z]{3,4}', 'series' => '.+', 'format' => 'full|' . implode('|', array_keys($conf->getFormats())))); //404 handler $app->notFound(function () use($app) { $app->render('404.html.twig');
/** * Register the access control manager in the given Slim app. * Make the access control manager available via $app->auth and ensure it * is a singleton. * @param \Slim\Slim $app Reference to the parent Slim app. * @throw \InvalidArgumentException Thrown when $app is invalid (null). * @throw \LogicException Thrown when $app already has a referenced access control manager. */ public static function register(\Slim\Slim $app) { // Check parameter validity if (empty($app)) { throw new \ErrorException("Parent Slim app cannot be null !"); } $auth = $app->auth; if (!empty($auth)) { if ($auth instanceof \BenGee\Slim\Auth\AccessControlManager) { throw new \LogicException("An instance of the access control manager is already registered !"); } else { throw new \LogicException("An instance of another access control manager is already registered under 'auth' resource name !"); } } // Register access control manager as a singleton inside app $class = __CLASS__; $auth = new $class($app); $app->container->singleton('auth', function () use($auth) { return $auth; }); // Register hook to perform routes access control $app->hook('slim.before.dispatch', function () use($auth) { // If route access control is enabled ... if ($auth->isRouteControlEnabled()) { // ... then get name of matched route and control access to it $route = $auth->app()->router->getCurrentRoute()->getName(); $auth->controlRouteAccess($route); } }, ~PHP_INT_MAX); }
(new Bootstrap($app, new PdoAdapter($app->db, 'users', 'user', 'hash', new PasswordValidator()), new acl()))->bootstrap(); $app->config(array('log.enable' => true, 'templates.path' => '../templates', 'debug' => false)); $view->parserOptions = array('debug' => false, 'cache' => dirname(__FILE__) . '/../cache', 'auto_reload' => true); $view->parserExtensions = array(new TwigExtension()); }); $app->configureMode('development', function () use($app, $view) { (new Bootstrap($app, new DebugAdapter(), new acl()))->bootstrap(); $app->authenticator->authenticate("admin", "admin"); $app->config(array('log.enable' => false, 'templates.path' => '../templates', 'debug' => true)); $view->parserOptions = array('debug' => true, 'cache' => false); $view->parserExtensions = array(new TwigExtension(), new Twig_Extension_Debug()); }); $app->hook('slim.before.router', function () use($app) { if ($app->auth->hasIdentity()) { $authData = $app->auth->getIdentity(); $authData['department_name'] = getNameForID($app->db, $authData['department']); $app->view()->appendData(array('userInfo' => $authData)); } $app->view()->appendData(array('site_root' => $app->environment['SCRIPT_NAME'] . '/')); }); $app->get('/', function () use($app) { $app->render('html/index.html'); })->name('index'); $app->get('/login', function () use($app) { $app->render('html/login.html'); })->name('login'); $app->post('/login', function () use($app) { $result = $app->authenticator->authenticate($app->request->post('username'), $app->request->post('password')); if ($result->isValid()) { $app->redirect($app->urlFor('profile')); } else { $app->flash('error', 'Invalid username or password provided');
use Slim\Views\Twig; use Slim\Views\TwigExtension; use Noodlehaus\Config; ini_set('display_errors', 1); error_reporting(E_ALL); //Define Main Root define("INC_ROOT", dirname(__DIR__)); //Define Globals require_once INC_ROOT . "/app/config/globals.php"; //Database Info require_once CONFIG_ROOT . "/db.php"; //Composer Autoloader require_once INC_ROOT . "/vendor/autoload.php"; //Create Slim App $app = new Slim(["debug" => true, "mode" => file_get_contents(INC_ROOT . "/app/mode.php"), "view" => new Twig(), "templates.path" => VIEWS_ROOT, "routes.case_sensitive" => false, "cookies.encrypt" => true, "cookies.secret_key" => "some_secret", "cookies.cipher" => MCRYPT_RIJNDAEL_256, "cookies.cipher_mode" => MCRYPT_MODE_CBC]); //Hooks $app->hook('slim.before', function () use($app) { $app->view()->appendData(array('siteUrl' => $app->config->get("template_data.url"))); }); //Set Configuration $app->configureMode($app->config("mode"), function () use($app) { $app->config = Config::load(CONFIG_ROOT . "/{$app->config("mode")}.php"); }); //Include Routes include ROUTES_ROOT . "/routes.php"; //Twig Configuration $view = $app->view(); $view->parserOptions = ["debug" => $app->config->get("view.debug")]; $view->parserExtensions = [new TwigExtension()]; //Include Filters require_once FILTERS_ROOT . "/filters.php";
// } }; }; $app = new Slim(array('view' => new \Slim\Views\Twig())); $view = $app->view(); $view->parserOptions = array('debug' => true); $app->add(new SessionCookie(array('name' => 'session', 'secret' => 'secret', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC))); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); $app->hook('slim.before.dispatch', function () use($app) { $usr = null; $sid = null; // if (isset($_SESSION['user'])) { // $user = $_SESSION['user']; // } if (isset($_SESSION['sid'])) { $sid = $_SESSION['sid']; } if (isset($_SESSION['usr'])) { $usr = $_SESSION['usr']; } $app->view()->setData('usr', $usr); $app->view()->setData('sid', $sid); }); /** * HOME ROUTE **/ $app->get('/', function () use($app, $dl) { $app->render('home.twig', array('code' => $app->getCookie('code'), 'email' => $app->getCookie('email'), 'album' => $app->getCookie('album'), 'subscribe' => $app->getCookie('subscribe'), 'albums' => $dl->get_albums())); })->name('home'); /** * HOME ROUTE POST HANDELING
<?php use ComPHPPuebla\Slim\Hook\PhpSettingsHook; use ComPHPPuebla\Slim\Handler\ErrorHandler; use ComPHPPuebla\Slim\Handler\NotFoundHandler; use ComPHPPuebla\Slim\Middleware\JsonpMiddleware; use ComPHPPuebla\Slim\Middleware\ContentNegotiationMiddleware; use ComPHPPuebla\Slim\Middleware\HttpCacheMiddleware; use Slim\Slim; use Api\Station\StationRoutes; use Api\ApplicationContainer; use Api\Station\StationContainer; chdir(__DIR__); require 'vendor/autoload.php'; $app = new Slim(require 'config/app.config.php'); $app->notFound(new NotFoundHandler($app)); $app->error(new ErrorHandler($app)); $app->hook('slim.before', new PhpSettingsHook(require 'config/phpini.config.php')); $container = new ApplicationContainer(); $container->register($app); $app->add(new HttpCacheMiddleware($app->cache)); $app->add(new ContentNegotiationMiddleware()); $app->add(new JsonpMiddleware()); $stationContainer = new StationContainer(); $stationContainer->register($app); $stationRoutes = new StationRoutes($app); $stationRoutes->register();
public function hook($name, $callable, $priority = 10, $override = false) { if ($override) { $this->clearHooks($name); } return parent::hook($name, $callable, $priority); }
if (PHP_SAPI !== 'cli') { $app->url = Url::createFromServer($_SERVER); } // Error handling $app->error(function (\Exception $e) { $code = $e->getCode(); if ($code < 100) { $code = 500; } Resource::error($code, $e->getMessage()); }); // Database layer setup $app->hook('slim.before', function () use($app) { $app->container->singleton('mongo', function () use($app) { $client = new Client($app->config('database')['host_uri']); $client->map([$app->config('database')['db_name'] => '\\API\\Collection']); $client->useDatabase($app->config('database')['db_name']); return $client; }); }); // CORS compatibility layer (Internet Explorer) $app->hook('slim.before.router', function () use($app) { if ($app->request->isPost() && $app->request->get('method')) { $method = $app->request->get('method'); $app->environment()['REQUEST_METHOD'] = strtoupper($method); mb_parse_str($app->request->getBody(), $postData); $parameters = new Set($postData); if ($parameters->has('content')) { $content = $parameters->get('content'); $app->environment()['slim.input'] = $content; $parameters->remove('content'); } else {
/** * Assign hook * @param string $name The hook name * @param mixed $callable A callable object * @param int $priority The hook priority; 0 = high, 10 = low */ public function hook($name, $callable, $priority = 10) { //parent::hook($name, $callable, $priority ); parent::hook($name, $this->buildCallable($callable), $priority); }
<?php require '../vendor/autoload.php'; $config = (require_once __DIR__ . '/../config.php'); use FA\DI\Container; use Slim\Slim; // Prepare app $app = new Slim($config['slim']); $container = new Container($app, $config); $app->hook('slim.before.router', function () use($app, $container) { $users = count($container['userDao']->findAll()); $pathInfo = $app->request->getPathInfo(); if ($users < 1 && $pathInfo != '/setup') { return $app->redirect('/setup'); } }); $app->get('/setup', function () use($app, $container) { if (count($container['userDao']->findAll()) > 0) { $app->halt(403); } $app->render('setup.html'); }); $app->post('/setup', function () use($app, $container) { if (count($container['userDao']->findAll()) > 0) { $app->halt(403, 'NO MOAR USERS ALLOWED'); } $params = $app->request()->post(); $email = filter_var($params['email'], FILTER_SANITIZE_EMAIL); $email = filter_var($email, FILTER_VALIDATE_EMAIL); if ($email) { try {
$pdo = new PDO($dsn, $dbuser, $dbpass); $db = new NotORM($pdo); return $db; }); $db = $app->db; $capsule = new Capsule(); $capsule->addConnection(['driver' => $app->config->get('db.driver'), 'host' => $app->config->get('db.host'), 'database' => $app->config->get('db.name'), 'username' => $app->config->get('db.username'), 'password' => $app->config->get('db.password'), 'charset' => $app->config->get('db.charset'), 'collation' => $app->config->get('db.collation'), 'prefix' => $app->config->get('db.prefix')]); $capsule->bootEloquent(); /* ============================================ VIEWS ===============================================*/ $view = $app->view(); $view->parserOptions = ['debug' => $app->config->get('twig.debug')]; $view->parserExtensions = [new TwigExtension()]; $app->hook('slim.before', function () use($app) { $app->view()->appendData(array('AssetsURL' => $app->config->get('app.staticUrl'), 'baseAdminURL' => $app->config->get('app.adminUrl'))); }); /* ============================================ Custom Models ===============================================*/ $app->container->set('user', function () { return new User(); }); $app->container->singleton('hash', function () use($app) { return new Hash($app->config); }); $app->container->singleton('validation', function () use($app) { return new Validator($app->user); }); $app->container->singleton('randomlib', function () use($app) { $factory = new RandomLib();