Tom IT

SlimPHP 2.x Custom Classes for Routes

If you want custom classes for your slim project you can do so by adding a route in the index.php file like this:

<?php
require 'vendor/autoload.php';

$app = new \Slim\App;
$app->get('/hello/:name','Namespace\Controller:function');
$app->run();
?>

Now if your namespace is called foo and the Class bar with a function baz you then your file foo/bar.php will look like:

<?php
namespace foo;

class Bar{
public function baz($name){
  echo 'hello ' . $name . '!';
}
}

To Get to the $app variable in the custom class (for getting post variables for instance) you can add this to your Class:

protected $_app;

public function __construct() {
        $this->_app = \Slim\Slim::getInstance();
       
    }

If you will be having a lot of classes, you can add this to a parent class, and have Bar extend that class Like so:

<?php
namespace Foo;
Class BaseClass{
protected $_app;
public function __construct()
{
  $this->_app = \Slim\Slim::getInstance();
}
}
?>
Other file:
<?php
namespace Foo;

class Bar extends BaseClass{
public function __construct()
{
  parent::construct();
}
public function baz($name){
  echo 'hello ' . $name . '!';
}
}
?>

 

Add Comment