public function __construct() { $view = new \Slim\Views\Twig(); $app = new \Slim\Slim(array('debug' => DEBUG, 'view' => $view, 'templates.path' => HOME . '/' . APP . '/View')); $app->notFound(function () use($app) { $app->render('errors/404.html'); }); $controllerFactory = new \Core\ControllerFactory($app); // the class that builds the controllers $view->parserExtensions = array(new \MyTwigExtension($controllerFactory)); $mainRoute = '/'; if (!empty(SUB_FOLDER)) { // is the whole site in a subdirectory? $mainRoute .= SUB_FOLDER . '(/)'; } $checkQueries = function ($q) { // our queries must be numerical for security's sake if (!empty($q)) { if (!is_numeric($q)) { return false; } if ($q <= 0) { return false; } } return true; }; $app->group($mainRoute, function () use($app, $checkQueries, $controllerFactory) { // the admin route $app->map(ADMIN_FOLDER . '(/)(:controller)(/)(:action)(/)(:query)(/)', function ($controller = '', $action = '', $query = '') use($app, $checkQueries, $controllerFactory) { if (false === $checkQueries($query)) { $app->notFound(); } else { $controllerFactory->buildController($controller, $action, true, $query); } })->via('POST', 'GET'); // front end routing $app->map('(:controller)(/)(:action)(/)(:query)(/)(:query2)(/)', function ($controller = '', $action = '', $query = '', $query2 = '') use($app, $checkQueries, $controllerFactory) { if (false === $checkQueries($query) || false === $checkQueries($query2)) { $app->notFound(); } else { $controllerFactory->buildController($controller, $action, false, $query, $query2); } })->via('POST', 'GET'); }); $app->run(); // run Slim Application }
static function generate($sRoot, $sPattern) { $app = new \Slim\Slim(array('view' => new \PHPView\PHPView(), 'templates.path' => getcwd())); $ite = new \RecursiveDirectoryIterator($sRoot); foreach (new \RecursiveIteratorIterator($ite) as $filename) { if (preg_match("/" . $sPattern . "\$/", $filename) && strpos($filename, "/_") === false) { $nTime = filemtime($filename); $sOutfile = str_replace("phtml", "", $filename); $nTime2 = 0; if (file_exists($sOutfile)) { $nTime2 = filemtime($sOutfile); } //if($nTime2 < $nTime){ ob_start(); $sPage = preg_replace("/[\\.\\/]/", "", $sOutfile); $app->render($filename, array("page" => $sPage)); file_put_contents($sOutfile . "html", ob_get_contents()); ob_end_clean(); //} } } }
include 'ChromePhp.php'; require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../models/productMgr.php'; require_once __DIR__ . '/../models/blogMgr.php'; require_once __DIR__ . '/../models/mailer.php'; $oProductMgr = new ProductMgr(); $oBlogMgr = new BlogMgr(); $oApp = new \Slim\Slim(array('templates.path' => __DIR__ . '/../views')); date_default_timezone_set('Canada/Saskatchewan'); $oApp->add(new \Slim\Middleware\SessionCookie(array('expires' => '60 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'slim_session', 'secret' => 'CHANGE_ME', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC))); /*** * Home page ***/ $oApp->get('/', function () use($oApp, $oProductMgr) { $oApp->render('home.phtml', array('title' => '', 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => 'Action', 'productsInGenre' => $oProductMgr->getProductsByGenre('Action'), 'featuredProducts' => $oProductMgr->getFeaturedProducts())); }); $oApp->get('/home/:genre', function ($sGenre) use($oApp, $oProductMgr) { $oApp->render('home.phtml', array('title' => $sGenre, 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => $sGenre, 'productsInGenre' => $oProductMgr->getProductsByGenre($sGenre), 'featuredProducts' => $oProductMgr->getFeaturedProducts())); }); // called when user search for items $oApp->post('/search', function () use($oApp, $oProductMgr) { $sKeywords = $oApp->request()->post('keywords'); $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords)); }); $oApp->get('/search', function () use($oApp, $oProductMgr) { $sKeywords = $oApp->request->params('keywords'); //ChromePhp::info($sKeywords); //die(); $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords)); });
<?php require __DIR__ . '/utility.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->notFound(function () use($dati, $app) { $app->render('shared/404.php', array('dati' => $dati)); }); $app->get('/', function () use($dati, $app) { $app->render('index.php', array('dati' => $dati)); })->name('index'); $app->map('/contattaci', function () use($dati, $app) { $app->render('email.php', array('dati' => $dati)); if (fatto()) { $app->redirect($app->urlFor('index')); } })->via('GET', 'POST'); $app->map('/templates(/:name+)', function ($name) use($dati, $app) { $app->render('shared/404.php', array('dati' => $dati)); })->via('GET', 'POST'); $app->get('/guida/:id', function ($id) use($dati, $app) { $app->render('index.php', array('dati' => $dati, 'guida' => $id)); }); $app->get('/logout', function () use($dati, $app) { $app->render('login/logout.php', array('dati' => $dati)); $app->redirect($app->urlFor('index')); }); if (!$dati['debug'] || isAdminUserAutenticate()) { $app->map('/login', function () use($dati, $app) { $app->render('login/index.php', array('dati' => $dati)); if (isUserAutenticate()) {
require '../../lib/db.php'; require '../../lib/Classes/Config.php'; $slim = new \Slim\Slim(array('debug' => true, 'view' => new \Slim\Views\Twig())); $view = $slim->view(); $view->parserOptions = array('debug' => true); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); /** Root URL */ $slim->get('/', function () use($slim) { $slim->response()->redirect('index.php/index'); }); /** The index page */ $slim->get('/index', function () use($slim) { $slim->render('index.php'); }); /** The enrolment page */ $slim->get('/enrol', function () use($slim) { // $slim->contentType('application/x-apple-aspen-config'); $config = get_config(); if (!isset($config)) { $config = array("access_rights" => 1024, "organisation_name" => "Abstractec", "master_profile_uuid" => "1234", "cert_uuid" => "4567", "mdm_uuid" => "7890", "mdm_certificate" => "certificate", "mdm_certificate_password" => "password", "mdm_topic" => "com.abstractec.mdm", "check_in_url" => "http://127.0.0.1:8888/~jimbob/service/checkin", "service_url" => "http://127.0.0.1:8888/~jimbob/service"); } $slim->response->headers->set('Content-Type', 'application/x-apple-aspen-config'); $slim->render('profile.php', array("config" => $config)); })->name('enrol'); $slim->run();
// Va a devolver un objeto JSON con los datos de usuarios. // Preparamos la consulta a la tabla. $consulta = $db->prepare("select * from soporte_usuarios"); // Ejecutamos la consulta (si fuera necesario se le pasan parámetros). $consulta->execute(); // Ejemplo sencillo de paso de variables a una plantilla. /* $app->render('miplantilla.php', array( 'name' => 'John', 'email' => '[email blocked]', 'active' => true ) ); */ // Desde dentro de la vista accederemos directamente a $resultados para gestionar su contenido. $app->render('listadousuarios.php', array('resultados' => $consulta->fetchAll(PDO::FETCH_ASSOC))); }); // Cuando accedamos a /nuevousuario se mostrará un formulario de alta. $app->get('/nuevousuario', function () use($app) { $app->render('nuevousuario.php'); })->name('altausuarios'); // Ruta que recibe los datos del formulario $app->post('/nuevousuario', function () use($app, $db) { // Para acceder a los datos recibidos del formulario $datosform = $app->request; // Los datos serán accesibles de esta forma: // $datosform->post('apellidos') // Preparamos la consulta de insert. $consulta = $db->prepare("insert into soporte_usuarios(idusuario,nombre,apellidos,email)\n\t\t\t\tvalues (:idusuario,:nombre,:apellidos,:email)"); $estado = $consulta->execute(array(':idusuario' => $datosform->post('idusuario'), ':nombre' => $datosform->post('nombre'), ':apellidos' => $datosform->post('apellidos'), ':email' => $datosform->post('email'))); if ($estado) {
$app->setName('Talententest Admin'); // Include Wordpress header for authentication if ($app->request->getResourceUri() == '/login') { define('WP_USE_THEMES', false); // Do not show themes require $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'wp-blog-header.php'; } $view = $app->view(); $view->parserOptions = array('debug' => true, 'cache' => dirname(__FILE__) . '/cache'); $view->parserExtensions = array(new \Slim\Views\TwigExtension(), new Twig_Extension_Debug()); $data = array(); $data['base_url'] = '/admin/'; $data['current_url'] = rtrim($data['base_url'], '/') . $app->request->getResourceUri(); $data['mainmenu'] = array(array('title' => 'Dashboard', 'url' => 'dashboard', 'icon' => 'fa-dashboard'), array('title' => 'Gebruikers', 'url' => 'users_overview', 'icon' => 'fa-users'), array('title' => 'Scholen', 'url' => 'schools_overview', 'icon' => 'fa-university'), array('title' => 'Talenten', 'url' => 'talents_overview', 'icon' => 'fa-tasks'), array('title' => 'Vaardigheden', 'url' => 'skills_overview', 'icon' => 'fa-sliders'), array('title' => 'Beroepen', 'url' => 'occupations_overview', 'icon' => 'fa-briefcase'), array('title' => 'Uitloggen', 'url' => 'logout', 'icon' => 'fa-lock')); $app->notFound(function () use($app, $data) { $app->render('404.html', $data); }); $app->get('/dashboard(/:school_id)', function ($school_id = null) use($app, $data) { $data['active_school_id'] = $school_id; if ($school_id == null) { $users = User::with('talents', 'skills', 'educationLevel')->get(); } else { $users = User::with('talents', 'skills', 'educationLevel')->where('school_id', '=', (int) $school_id)->get(); } $occupations = Occupation::all(); $schools = School::orderBy('name', 'ASC')->get(); $talents = Talent::all(); $data['schools'] = $schools->toArray(); $data['total_occupations'] = $occupations->count(); $data['total_users'] = $users->count(); $users_male = $users->filter(function ($user) {
// Prepare view $app->view(new \Slim\Views\Twig()); $app->view->parserOptions = array('charset' => 'utf-8', 'cache' => realpath('../app/templates/cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); // Define routes $app->get('/', function () use($app) { $systemDir = __DIR__ . '/../storage/data/system'; $snippetsDir = __DIR__ . '/../storage/data/snippets'; $packageDir = __DIR__ . '/../storage/data/packages'; $systemFiles = glob($systemDir . '/*.txt'); $snippetFiles = glob($snippetsDir . '/*.txt'); $packageFiles = glob($packageDir . '/*.txt'); $data['system_entries'] = buildMenu($systemFiles); $data['snippet_entries'] = buildMenu($snippetFiles); $data['package_entries'] = buildMenu($packageFiles); $app->render('home.twig', $data); }); function buildMenu($files) { $menu = array(); if (!empty($files)) { foreach ($files as $file) { $dataArray = explode('---', file_get_contents($file)); // remove spaces $dataArray = array_map('trim', $dataArray); // don't include items not containing "code" element if (empty($dataArray[1])) { continue; } $menu[] = array('name' => $dataArray[0], 'code' => $dataArray[1], 'autorun' => $dataArray[2]); }
} function mark_footprint($user_id) { if ($user_id != current_user()['id']) { $query = 'INSERT INTO footprints (user_id,owner_id) VALUES (?,?)'; db_execute($query, array($user_id, current_user()['id'])); } } function prefectures() { static $PREFS = array('未入力', '北海道', '青森県', '岩手県', '宮城県', '秋田県', '山形県', '福島県', '茨城県', '栃木県', '群馬県', '埼玉県', '千葉県', '東京都', '神奈川県', '新潟県', '富山県', '石川県', '福井県', '山梨県', '長野県', '岐阜県', '静岡県', '愛知県', '三重県', '滋賀県', '京都府', '大阪府', '兵庫県', '奈良県', '和歌山県', '鳥取県', '島根県', '岡山県', '広島県', '山口県', '徳島県', '香川県', '愛媛県', '高知県', '福岡県', '佐賀県', '長崎県', '熊本県', '大分県', '宮崎県', '鹿児島県', '沖縄県'); return $PREFS; } $app->get('/login', function () use($app) { $app->view->setLayout(null); $app->render('login.php', array('message' => '高負荷に耐えられるSNSコミュニティサイトへようこそ!')); }); $app->post('/login', function () use($app) { $params = $app->request->params(); authenticate($params['email'], $params['password']); $app->redirect('/'); }); $app->get('/logout', function () use($app) { $_SESSION['user_id'] = null; $app->redirect('/login'); }); $app->get('/', function () use($app) { authenticated(); $profile = db_execute('SELECT * FROM profiles WHERE user_id = ?', array(current_user()['id']))->fetch(); $entries_query = 'SELECT * FROM entries WHERE user_id = ? ORDER BY created_at LIMIT 5'; $stmt = db_execute($entries_query, array(current_user()['id']));
<?php ini_set('display_errors', 1); define('BASE_DIR', __DIR__ . "/.."); require BASE_DIR . '/vendor/autoload.php'; // Slim application instance $app = new \Slim\Slim(array('view' => new \Slim\Views\Twig(), 'templates.path' => BASE_DIR . '/app/views/')); $app->setName('gumaz/slim-base-mvc-json'); // Handling 404 error $app->notFound(function () use($app) { $message = ['message' => 'My custom error message!']; $app->render('not-found.html', $message); }); // Automatically load router files $routers = glob(BASE_DIR . '/routers/*.router.php'); foreach ($routers as $router) { require $router; } $app->run();
} } if ($error) { // Required field(s) are missing or empty // echo error json and stop the app $response = array(); $app = \Slim\Slim::getInstance(); $response["error"] = true; $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty'; $app->render('default.php', $response, 400); $app->stop(); } } $app->get('/', function () use($app) { $data = array('status' => '200'); $app->render('default.php', $data, 200); }); $app->group('/products', function () use($app) { //list //delete id //update id //ADD $app->post('/upload', function () use($app) { if (!isset($_FILES['file'])) { echo "No files uploaded!!"; return; } $file = $_FILES['file']; if ($file['error'] !== 0) { echo "Error no upload!!"; return;
}); // $log = $app->getLog(); // $view = $app->view(); $app->configureMode('development', function () use($app, $config) { $app->config(array('debug' => true)); $connection_name = 'testing'; include '../app/app.php'; }); $app->configureMode('production', function () use($app, $config) { $app->config(array('debug' => false)); $connection_name = 'default'; include '../app/app.php'; }); $app->get('/', function () use($app, $config) { if ($config['maintenance']) { $app->render('home/maintenance.php', array()); } else { $app->render('home/index.php', array()); } }); $app->get('/setup', function () use($app, $config) { include '../app/functions.setup.php'; setup($config); }); $app->notFound(function () use($app) { $app->render('404.html'); }); $app->error(function (\Exception $e) use($app) { $app->log->error($e->getFile() . ' on ' . $e->getLine() . ' ' . ' because : ' . $e->getMessage()); $app->response->headers->set('Content-Type', 'text/html'); $app->render('500.html');
<?php session_start(); require 'vendor/autoload.php'; require 'rb.php'; R::setup('sqlite:subscribers.sqlite'); $twig_vars = lib\SlimCMS::getTwigVars(); $config = $twig_vars['config']; // Setup custom Twig view $twigView = new \Slim\Views\Twig(); $app = new \Slim\Slim(array('debug' => true, 'view' => $twigView, 'templates.path' => "themes/" . $config["theme"] . "/", 'twigVars' => $twig_vars)); $app->view->parserOptions = array('charset' => 'utf-8', 'auto_reload' => true, 'autoescape' => false); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); $app->notFound(function () use($app) { $twig_vars = lib\SlimCMS::getTwigVars(); $app->render('404.html.twig', $twig_vars); }); $authenticate = function ($app) { return function () use($app) { if (!isset($_SESSION['user'])) { $app->flash('error', 'Login required'); $app->redirect('/admin'); } }; }; /*********************************************************************************************************************** * ADMIN BLOCK **********************************************************************************************************************/ // Admin $app->get('/admin/', function () use($app) { $twig_vars = $app->config('twigVars');
<?php require 'vendor/autoload.php'; $app = new \Slim\Slim(); $app->config(array('debug' => true, 'templates.path' => 'client/views/')); $app->get('/', function () use($app) { $app->render('index.html'); }); $app->get('/date', function () use($app) { echo date('Y-m-d H:i:s'); }); $app->notFound(function () use($app) { $app->render('index.html'); }); $app->run();
$history = $fcache->get('hash_history'); if (!$history) { $history = array(); } if (array_key_exists($chars, $history)) { return array_keys($history); } if (count($history) > $max) { $key_del = array_rand($history, 1); unset($history[$key_del]); } $history[$chars] = ''; $fcache->add('hash_history', $history); return array_keys($history); } // GET route $app->get('/', function () use($app) { $chars = 'DigHash'; $random = get_randoms(20); $history = do_history($chars); $app->render('hash.html', array('chars' => $chars, 'hash_rst' => cal_hash($chars), 'random' => $random, 'history' => $history)); }); $app->get('/:chars.html', function ($chars) use($app) { $random = get_randoms(20); $history = do_history($chars); $app->render('hash.html', array('chars' => $chars, 'hash_rst' => cal_hash($chars), 'random' => $random, 'history' => $history)); }); $app->notFound(function () use($app) { $app->redirect('/', 301); }); $app->run();
return false; } } } return true; } $app->group('/', function () use($app, $dbsettings) { $username = $app->request()->headers('PHP_AUTH_USER'); $password = $app->request()->headers('PHP_AUTH_PW'); if ($username != $dbsettings->dbuser || $password != $dbsettings->dbpass) { $app->response()->status(401); $app->response()->header('WWW-Authenticate', sprintf('Basic realm="%s"', 'Protected Area')); return; } $app->get('/', function () use($app) { $app->render('app.html'); }); $app->post('procparams', function () use($app) { $entry = json_decode($app->request()->getBody()); echo getInputParams($entry); }); $app->get('api', function () use($app) { $app->render('../../api/api.json'); }); $app->post('api', function () use($app) { $json = $app->request()->getBody(); $data = json_decode($json); // TODO: CHECK INPUT FOR VALIDITY // GENERATE SQL CODE FOR PROCEDURES $mysqli = getConnection_mysqli(); // Set the procedures according to the existing API when an error occurs
<?php error_reporting(E_ALL); ini_set('display_errors', 1); require __DIR__ . '/vendor/autoload.php'; $app = new \Slim\Slim(array('debug' => true, 'templates.path' => './templates')); $app->get('/', function () { echo "Hello pankaj"; }); $app->get('/books/:id', function ($id) use($app) { $app->render('myTemplate.php', array('id' => $id)); }); $app->get('/hello/:name', function ($name) { echo "Hello, {$name}"; }); $app->run();
<?php require "../vendor/autoload.php"; require "../vendor/phpmailer/phpmailer/PHPMailerAutoload.php"; require "../vendor/phpmailer/phpmailer/function.php"; $app = new \Slim\Slim(); $app->config(array('debug' => true, 'templates.path' => '../views')); $db = new PDO("mysql:host=localhost;dbname=projeto", "root", "root"); $app->get('/', function () use($app) { $app->render("index.php"); }); $app->get('/novo/nome', function () use($app, $db) { $app->render('novo.php'); }); $app->post('/', function () use($app, $db) { $request = $app->request; $name = $request->post('name'); $email = $request->post('email'); $site = $request->post('site'); $inquiry = $request->post('inquiry'); if ($name == '' || $email == '' || $site == '' || $inquiry == '') { $app->redirect("index.php"); } else { $dbquery = $db->prepare("INSERT INTO inquiry(name,email,website,inquiry) VALUES(:name,:email,:site,:inquiry)"); $dbquery->execute(array(":name" => $name, ":email" => $email, ":site" => $site, ":inquiry" => $inquiry)); } $app->redirect("index.php"); }); $app->get('/send_email', function () use($app) { send_email(); });
umask($old); $log = new \Monolog\Logger(strtoupper($app->request->getHost())); $log->pushHandler(new \Monolog\Handler\StreamHandler($logfile, \Monolog\Logger::DEBUG, true, 0777)); return $log; }); /** * Register handlers */ \Monolog\ErrorHandler::register($app->log); /** * Error handle */ $app->error(function (\Exception $e) use($app) { $app->applyHook('log.request.info', $e->getMessage()); $app->log->error($e); $app->render('error.php'); }); $app->notFound(function () use($app) { $app->applyHook('log.request.info', 'Page not found'); $app->render('404.php'); }); // throw new \Exception('test error'); /** * Define hooks */ if (file_exists(APPPATH . 'hooks.php')) { require APPPATH . 'hooks.php'; } /** * Define routes */
if(!$stmt->bind_result($eventID)){ error_log("Bind Result failed: (" . $stmt->errno . ") " . $stmt->error); $app->response->setStatus(500); return; } $stmt->fetch(); $stmt->close(); echo "EventID:".$eventID; */ //workaround for query switch ($code) { case "gi2015": $eventID = 1; break; case "gi2015a": $eventID = 2; break; case "gi2015b": $eventID = 3; break; } $ip = $app->request->headers->get('x-forwarded-for'); if (!$mysqli->query("INSERT INTO `clicks` (`event_id`, `ip_address`) VALUES (" . $eventID . ", INET_ATON('" . $ip . "'))")) { error_log("Insert Query failed: (" . $mysqli->errno . ") " . $mysqli->error); $app->response->setStatus(500); return; } $mysqli->close(); $app->render($code . ".html"); }); $app->run();
*/ $admin_app->add(new \Slim\Middleware\SessionCookie(array('expires' => $config['_cookies.lifetime']))); /* |-------------------------------------------------------------------------- | Check for Disabled Control Panel |-------------------------------------------------------------------------- | | We need to make sure the control panel is enabled before moving any | further. You know, security and stuff. | */ $admin_enabled = Config::get('_admin_enabled', true); if ($admin_enabled !== true && strtolower($admin_enabled) != 'yes') { Statamic_View::set_templates(array_reverse(array("denied"))); Statamic_View::set_layout("layouts/disabled"); $admin_app->render(null, array('route' => 'disabled', 'app' => $admin_app)); exit; } /* |-------------------------------------------------------------------------- | Set Default Layout |-------------------------------------------------------------------------- | | This may be overwritten later, but let's go ahead and set the default | layout file to start assembling our front-end view. | */ Statamic_View::set_layout("layouts/default"); /* |-------------------------------------------------------------------------- | Set Global Variables, Defaults, and Environments
// ========== COMPOSER ========== require ROOT_PATH . '/vendor/autoload.php'; // ========== CONFIGURATION ========== $config = (require APP_PATH . '/src/config.php'); // ========== PHP (from configuration) ========== // time zone date_default_timezone_set($config['PHP']['default_timezone']); // errors ini_set('display_errors', $config['PHP']['display_errors']); ini_set('display_startup_errors', $config['PHP']['display_startup_errors']); ini_set('log_errors', $config['PHP']['log_errors']); // session if (true === $config['PHP']['need_session']) { session_cache_limiter(false); session_set_cookie_params(0, '/', '', $config['PHP']['session_cookie_secure'], true); session_start(); } unset($config['PHP']); // ========== SLIM ========== $app = new \Slim\Slim($config['Slim']); $app->config('app', $config['App']); $app->view()->setData('config', $app->config('app')); require APP_PATH . '/src/dependencies.php'; require APP_PATH . '/src/middlewares.php'; require APP_PATH . '/src/routes.php'; // Error handler $app->error(function (\Exception $e) use($app) { $app->getLog()->error($e); $app->render('errors/error.twig'); }); $app->run();
/** * Test render with template and data and status */ public function testRenderTemplateWithDataAndStatus() { $s = new \Slim\Slim(array('templates.path' => dirname(__FILE__) . '/templates')); $s->get('/bar', function () use($s) { $s->render('test.php', array('foo' => 'bar'), 500); }); $s->call(); list($status, $header, $body) = $s->response()->finalize(); $this->assertEquals(500, $status); $this->assertEquals('test output bar', $body); }
* your Slim application now by passing an associative array * of setting names and values into the application constructor. */ $app = new \Slim\Slim(); /** * Step 3: Define the Slim application routes * * Here we define several Slim application routes that respond * to appropriate HTTP request methods. In this example, the second * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete` * is an anonymous function. */ $app->get('/', function () use($app) { $posts = \Slim\DB::getInstance()->select()->from('post')->orderBy('created', 'desc')->execute()->fetchAll(PDO::FETCH_OBJ); $app->view('Slim\\View\\Layout'); $app->render('index.php', ['posts' => $posts]); })->name('home'); $app->get('/post/:id', function ($id) use($app) { $posts = \Slim\DB::getInstance()->select()->from('post')->where('id', '=', $id)->orderBy('created', 'desc')->execute()->fetchAll(PDO::FETCH_OBJ); if ($posts) { $app->view('Slim\\View\\Layout'); $app->render('post.php', ['post' => $posts[0]]); } else { $app->notFound(); } })->name('post'); /* Admin area*/ $app->get('/admin', 'Slim\\Admin:indexAction')->name('admin-home'); $app->get('/admin/new', 'Slim\\Admin:newAction')->name('post-new'); $app->post('/admin/save', 'Slim\\Admin:saveAction')->name('post-save'); $app->post('/admin/login', 'Slim\\Admin::loginAction')->name('login');
<?php ini_set("display_errors", "1"); ini_set("error_reporting", E_ALL & ~(defined('E_STRICT') ? E_STRICT : 0)); require '../vendor/autoload.php'; require '../config.php'; // Setup custom Twig view $twigView = new \Slim\Views\Twig(array('debug' => true)); $app = new \Slim\Slim(array('debug' => true, 'view' => $twigView, 'templates.path' => '../templates/')); $app->notFound(function () use($app) { $app->render('404.html'); }); // Automatically load router files $routers = glob('../routers/*.router.php'); foreach ($routers as $router) { require $router; } $app->run();
$app->container->singleton('api', function () use($app, $dbConfig) { return new API($dbConfig, $app->domain); }); function APIRequest() { $app = \Slim\Slim::getInstance(); $app->view(new \JsonApiView()); $app->add(new \JsonApiMiddleware()); $response = $app->response(); $response->header('Access-Control-Allow-Origin', '*'); } /** * View pages */ $app->get('/', function () use($app) { $app->render('shortener.php', array('revision' => 4)); }); $app->get('/:id+', function ($id) use($app) { $result = $app->api->getLinkById($id); if ($result != null) { $app->render('redirect.php', array('urlShortened' => $result['urlShortened'])); } else { $app->notFound(); } })->conditions(array('id' => '\\d+')); $app->get('/api', function () use($app) { $app->render('docs.php'); }); /** * API Methods */
$app = new \Slim\Slim(array('view' => new \Slim\Views\Twig())); $view = $app->view(); $view->parserOptions = array('debug' => true, 'cache' => dirname(__FILE__) . '/cache'); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); //dont ovveriden view /* $app = new \Slim\Slim(); */ //first example /* $app->get('/hello/:name', function ($name) { echo "Hello, $name"; }); */ $app->get('/', function () use($app) { $app->render('about.twig'); }); $app->get('/contact', function () use($app) { //DEBUG check it with name function $app->render('contact.twig'); }); $app->post('/contact', function () use($app) { $name = $app->request()->post('name'); $email = $app->request()->post('email'); $msg = $app->request()->post('msg'); if (!empty($name) && !empty($email) && !empty($msg)) { $claenName = filter_var($name, FILTER_SANITIZE_STRING); $claenEmail = filter_var($email, FILTER_SANITIZE_EMAIL); $claenMsg = filter_var($msg, FILTER_SANITIZE_STRING); } else { $app->redirect('contact');
<?php require __DIR__ . '/vendor/autoload.php'; $app = new \Slim\Slim(array('templates.path' => './assets/templates', 'debug' => true, 'view' => new \Slim\Views\Twig())); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension(), new \Twig_Extension_Debug()); $twig = $app->view->getInstance(); $filter = new \Twig_SimpleFilter('MyFunc', function ($val) { echo '---- ' . $val . '----'; }); $twig->addFilter($filter); $app->get('/', function () use($app) { $t = 1; $app->view->setData(array('foo' => $t)); $app->render('test.twig'); }); $app->run();
$session_identifier = Hybrid_Auth::storage()->get('user'); if (is_null($session_identifier) && $app->request()->getPathInfo() != '/login/') { $app->redirect('/login/'); } }; }; $app->get('/', function () use($app, $model) { $app->hybridInstance; $session_identifier = Hybrid_Auth::storage()->get('user'); $avatarUrl = $model->getAvatarUrl($session_identifier); if (isset($session_identifier) && !empty($session_identifier)) { $scriptID = 'i'; } else { $scriptID = '!i'; } $app->render('home.php', ['datajs' => 'home.js', 'datagroupjs' => '', 'name' => 'Home', 'avatarURL' => $avatarUrl, 'identifier' => $session_identifier, 'scriptID' => $scriptID]); })->name('home'); $app->get('/login/', $authenticate($app), function () use($app) { $app->render('login.php', ['datajs' => '', 'datagroupjs' => '', 'name' => 'Login']); }); $app->get('/login/:idp', function ($idp) use($app, $model) { try { $adapter = $app->hybridInstance->authenticate(ucwords($idp)); $user_profile = $adapter->getUserProfile(); if (empty($user_profile)) { $app->redirect('/login/?err=1'); } $identifier = $user_profile->identifier; if ($model->identifier_exists($identifier)) { $model->login_user($identifier); $app->redirect('/welcome/');
function getBaseURL() { $pageURL = 'http'; $pageURL .= "://" . $_SERVER["SERVER_NAME"]; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= ":" . $_SERVER["SERVER_PORT"]; } return $pageURL; } // opentok $opentok = new OpenTok($apiKey, $apiSecret); // setup slim framework $app = new \Slim\Slim(array('templates.path' => './templates')); // routes $app->get('/', function () use($app) { $app->render('customer.php'); }); // rep get details about an appointment $app->get('/getinfo/:timestamp', function ($timestamp) use($app, $con) { $result = sendQuery("SELECT * FROM Schedules WHERE Timestamp='{$timestamp}'"); $appointmentInfo = mysqli_fetch_assoc($result); header("Content-Type: application/json"); echo json_encode($appointmentInfo); }); // get availability of a certain day, used by both rep and customer $app->get('/availability/:daystring', function ($daystring) use($app, $con) { $result = sendQuery("SELECT timestamp FROM Schedules WHERE Daystring='{$daystring}'"); $data = []; while ($row = mysqli_fetch_array($result)) { array_push($data, $row['timestamp']); }