A
A
Artem2015-01-03 19:48:30
PHP
Artem, 2015-01-03 19:48:30

Routing in Slim: how to pass the $app object to a class function?

Hello.
I did not find in the documentation for the framework how to bind a specific method (for example, POST) to a class function. For example, there is a User class, we define the functions get(), create(), update(), etc., then we set up routing: each method to the corresponding function (GET->get(), POST->create( ), etc.) Do you think this is generally a normal architecture? Or what is the best way to do it?
I found this solution on stackoverflow: That is, home is a static function of the Pages class. But how then to use the $app object in it? I did not find any examples of developing something on Slim, only with a procedural paradigm .. PS. you need to write a RESTful API.
$app->get('/', '\Pages:home');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sl1m_dogg, 2016-01-05
@ber_enot

I didn’t quite understand the essence of the question, but apparently $app can be obtained from the global scope
another option from the documentation, but it’s better to look at the description of the arguments
$app->get('/foo', function () use ($app) {
$app ->render('foo.php'); // <-- SUCCESS
});

O
Oleg Maksimenko, 2016-09-12
@olegprof

You can also do this:
class \SiteController

class SiteController extends BaseController
{

    /**
     * @var
     */
    protected $ci;

    /**
     * @param Container $ci
     */
    public function __construct(Container $ci)
    {
        $this->ci = $ci;
    }

    /**
     * @param Request $request
     * @param Response $response
     * @param $args
     * @return \Psr\Http\Message\ResponseInterface|Response
     */
    public function actionIndex(Request $request, Response $response, $args)
    {
        /** @var \Slim\Views\PhpRenderer $renderer */
        $renderer = $this->ci->get('view');

        // some code

        return $response->withRedirect('/auth/');
    }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question