1 year ago
#74873
salihbey24
How can i pass library in BaseController to any Controller's constructer in codeigniter 4
i want use codeigniter's uri library in multiple pages.For this reason i created an instance of uri library in BaseController with named $uri
. I can use this library in my Home::index controller
but i can not use in Home::__construct
. Any suggestion?
BaseController.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = ["cookie"];
protected $session;
protected $parser;
protected $uri;
/**
* Constructor.
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = \Config\Services::session();
$this->parser = \Config\Services::parser();
// $this->uri = new \CodeIgniter\HTTP\URI(current_url(true));
$this->uri = service('uri');
$this->uri->setSilent();
// Preload any models, libraries, etc, here.
// E.g.: $this->session = \Config\Services::session();
}
}
class Home extends BaseController
{
public function __construct()
{
var_dump($this->uri);//line 16
}
public function index()
{
die(var_dump($this->uri));//line 21
}
}
C:\wamp64\www\ci4\app\Controllers\Home.php:16:null
C:\wamp64\www\ci4\app\Controllers\Home.php:21:
object(CodeIgniter\HTTP\URI)[11]
protected 'uriString' => null
protected 'segments' =>
array (size=0)
empty
protected 'scheme' => string 'http' (length=4)
protected 'user' => null
protected 'password' => null
protected 'host' => string 'localhost' (length=9)
protected 'port' => null
protected 'path' => string '/' (length=1)
protected 'fragment' => string '' (length=0)
protected 'query' =>
array (size=0)
empty
protected 'defaultPorts' =>
array (size=4)
'http' => int 80
'https' => int 443
'ftp' => int 21
'sftp' => int 22
protected 'showPassword' => boolean false
protected 'silent' => boolean true
protected 'rawQueryString' => boolean false
php
codeigniter
construct
0 Answers
Your Answer