I have the following structure in CI4 project:
app
pages
Front.php
Member.php
manage
Courses.php
Here are the routing rules:
$routes->group('pages', ['namespace' => 'App\Pages'], function ($routes) {
$routes->resource('member', ['only' => ['index', 'show']]);
$routes->group('manage', ['namespace' => 'App\Pages\Manage'], function ($routes) {
$routes->resource('courses', ['only' => ['index', 'update']]);
});
});
Front.php is the main controller.
namespace App\Pages;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
class Front extends \CodeIgniter\Controller
{
protected $me;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) {
parent::initController($request, $response, $logger);
$this->me = $this->run();
log_message('info', 'My id: ' . $this->me);
}
private function run() {
return 10;
}
protected function showVal($val) {
log_message('info', 'Value is: ' . $val);
}
}
Member.php extends Front.php.
namespace App\Pages;
class Member extends Front
{
protected $model;
public function __construct()
{
log_message('info', 'My id in Member: ' . $this->me);
helper('utils');
$this->model = model('App\Models\MemberModel');
}
public function index() {}
public function show($mid) {}
}
Accessing the URL website.com/pages/member produces the following log message:
My id: 10
My id in Member: 10
It means the front controller is properly initialized.
However, I'm failing to initialize the front controller from the subfolder controller.
namespace App\Pages\Manage;
use App\Pages\Front;
class Courses extends Front
{
public function __construct()
{
log_message('info', 'My id in Courses: ' . ($this->me ?? 'Not available'));
}
public function index() {}
public function update($cid) {
$this->showVal(100);
}
}
Accessing website.com/pages/manage/courses gives the following log:
My id in Courses is: not available
However, performing a PUT request on courses gives the log:
My id in Courses is: not available
Value is: 100
So the Courses controller is able to include the Front controller but can't get it initialized.
What am I missing?
I'm supposed to let it get initialized in the same manner as the Member controller gets.
Do I need to manually initialize it by calling parent::initController(...) in the courses class constructor?
Thanks for the help.
CodePudding user response:
In php __construct() doesn't call parent::__construct() automatically. initController() is also not called by any extending class automatically.
However calling (almost) any function from current instance will call initController(). You do instantiate a model in Member.php's constructor, which forced the shared instance.
A way to secure the initialization is just call initController() in extended constructors.