Skip to content

Instantly share code, notes, and snippets.

@acelot
Last active August 29, 2015 14:03
Show Gist options
  • Save acelot/c7bd2e1a4fea582c7af4 to your computer and use it in GitHub Desktop.
Save acelot/c7bd2e1a4fea582c7af4 to your computer and use it in GitHub Desktop.
slim controller, controllers for slim, slim framework, slim mvc, SlimControlled.php
<?php
namespace App\Controllers;
class Index
{
public function action_index()
{
echo 'Hello, world';
}
// This function has a greater advantage because here explicitly specified HTTP method GET
public function action_index_get()
{
echo 'Hello, my world';
}
}
<?php
/*
* Application init
*/
$app = new \App\SlimControlled();
/*
* Routes
*/
// Admin side. Note that the route must be before the default one.
$app->mapController('/admin(/:controller(/:action(/:param)))', 'App\\Controllers\\Admin')->name('admin');
// Default
$app->mapController()->name('public');
/*
* Start app
*/
$app->run();
<?php
namespace App;
class SlimControlled extends \Slim\Slim
{
public function mapController($routePattern = '/(:controller(/:action(/:param)))', $namespace = 'App\\Controllers')
{
return $this
->any(
$routePattern,
function ($controller = 'index', $action = 'index', $param = null) use ($namespace) {
$controller = str_replace(' ', '', ucwords(strtolower(str_replace('_', ' ', $controller))));
$className = $namespace . '\\' . $controller;
// Each action must start with 'action_' prefix. Also you can add HTTP method suffix like 'action_edit_post'.
$methods = array(
'action_' . $action . '_' . strtolower($this->request->getMethod()),
'action_' . $action
);
foreach ($methods as $method) {
$this->log->debug($className . '->' . $method);
if (method_exists($className, $method)) {
(new $className)->$method($param);
return;
}
}
$this->notFound();
}
)
->conditions(
array(
'controller' => '[a-z_]+',
'action' => '[a-z_]+',
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment