Last active
August 29, 2015 14:03
-
-
Save acelot/c7bd2e1a4fea582c7af4 to your computer and use it in GitHub Desktop.
slim controller, controllers for slim, slim framework, slim mvc, SlimControlled.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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