How to call models from other multi-application sites in a single installation of Codeigniter 4?
The folder structure looks like this:
- WebsiteFolder --Site1 ---app ---public --- tests --- writeable (.env, spark and other files) --Site2 ---app ---public --- tests --- writeable (.env, spark and other files) -- system
Here is my sample code:
At site 1
Constants.php I have defined a root directory to locate site2.
define('ROOTSOURCE', dirname(__DIR__,3) . '\site2');
This returns:
E:\Project\website\site2
Autoload.php
I have set up PSR4.
public $psr4 = [ APP_NAMESPACE => APPPATH, // For custom app namespace 'Config' => APPPATH . 'Config', 'Source\Models' => ROOTSOURCE . '/app/Models/' ];
Then I run the SPARK command:
php spark namespaces
and return
--------------- ------------------ -------------------------------------------------- --------------------- -------- | Namespace | Path | Found? | --------------- ---------------------------------- -------------------------------------------------- ---- -------- | CodeIgniter | E:\Project\DennisLiu\website\system | Yes | | App | E:\Project\DennisLiu\website\site1\app | Yes | | Config | E:\Project\DennisLiu\website\site1\app\Config | Yes | | Source\Models | E:\Project\DennisLiu\website\site2\app\Models | Yes | --------------- ---------------------------------- -------------------------------------------------- ---- --------
Then find the namespace Source\Models. So far so good.
Controller=> Home.php
namespace App\Controllers; use Source\Models; class Home extends BaseController { public function index() { $setting = new \Source\Models\Setting(); return view('welcome_message'); }
When I run the controller I get:
Class 'Source\Models\Setting' not found
Next step,
At site 2
I have the modelSettings in the Site2 models folder.
Note:
Everything is working fine in Site 2.
My problem is that I get the error "Class "Source\Models\Setting"" not found"The correct settings for calling site 2 models in a single application installation of codeigniter 4 are What? . < /p>
Note: This is a single installation of codeigniter 4 for both websites. I shared the system folder.
You can access the model in a class by creating a new instance or using the model() helper function.
Examples like this
I found the problem. This is the correct way to do this.
Folder structure
Controller - Home.php
Autoload.php
Constants.php
DBSetting.php
Namespace Sharing\Model; Using CodeIgniter\Model;
Class DBSetting extended model{
}
We can also call the model in site 2. Just set the correct path in Autoload.php to reference the model in site 2.
Notice:If a model in site 2 contains another model or link, if we call from site 1, the codeigniter 4 system will read the link, model from site 1. So make sure to call the normal model in site 2. Or just create a shared model folder as above.