Search code examples
codeigniter-4

How to use a librarie in views in Codeigniter4


i trie to use a own library in a view, but it failed with "undefined property: CodeIgniter\View\View::$mylib"

This is the Base Controller

protected $mylib;

    /**
     * Constructor.
     */
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
    
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);
        
        //--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.:
        // $this->session = \Config\Services::session();
        
        //Include our librarie with http-request
        $this->mylib = new mylib(service('request'));
    }

In the Controller i use it in this way, here i can work with my libray without any trouble. The testfunction will return a simple text.

namespace App\Controllers;

//Important to add our librarie (session, rbac, login etc.)

    use App\Libraries\mylib;
    ...
    die("Test: $this->mylib->testfunction());

If i try the same in my view file i recieve the error.

die("Test: $this->mylib->testfunction());

What i do wrong?

Update

In the meantime i find a way to work with my library in the views at top of my view-file i add this

use App\Libraries\mylib;
$this->mylib = new mylib(service('request'));

It works, but is there a way to make the whole thing easier so that I don't have to write these lines in every view-file but maybe only once in e.g. Base-Controller?


Solution

  • What i do wrong?

    You're assuming that because you created that Library in the Controller that it is automatically accessible in a View, which is incorrect, regardless if it's a class property of the Controller or not.

    Anything that is not already in the View needs to be passed in when you "use" it (i.e. the view() function's second parameter). So you can either create the Library in the Controller and pass the entire object into the View, or continue creating it directly in the View as you're doing now.

    The first option tends to be a little cleaner.