Access app in class in Slim Framework 3

前端 未结 5 1645
旧时难觅i
旧时难觅i 2021-02-05 23:33

Im having trouble understanding how to access the instance of Slim when a route is in a seperate class than index.php

When using Slim Framework 2 I always used the follo

5条回答
  •  遥遥无期
    2021-02-06 00:04

    I created the following base controller and extended from that. Only just started playing with Slim but it works if you need access to to the DI in your controllers.

    namespace App\Controllers;
    
    use Interop\Container\ContainerInterface;
    
    abstract class Controller
    {
        protected $ci;
    
        /**
         * Controller constructor.
         *
         * @param ContainerInterface $container
         */
        public function __construct(ContainerInterface  $container)
        {
            $this->ci = $container;
        }
    
        /**
         * @param $name
         * @return mixed
         */
        public function __get($name)
        {
            if ($this->ci->has($name)) {
                return $this->ci->get($name);
            }
        }
    }
    

    Then in your other controllers you can use it like this.

    namespace App\Controllers;
    
     /**
     * Class HomeController
     *
     * @package App\Controllers
     */
    class HomeController extends Controller
    {
    
        /**
         * @param $request
         * @param $response
         * @param $args
         * @return \Slim\Views\Twig
         */
        public function index($request, $response, $args)
        {
            // Render index view
            return $this->view->render($response, 'index.twig');
        }
    
    }
    

提交回复
热议问题