P粉4935341052023-09-01 20:04:17
You can access the model in a class by creating a new instance or using the model() helper function.
Examples like this
// Create a new class manually $userModel = new \App\Models\UserModel(); // Create a new class with the model function $userModel = model('App\Models\UserModel', false); // Create a shared instance of the model $userModel = model('App\Models\UserModel');
P粉7224099962023-09-01 10:37:48
I found the problem. This is the correct way to do this.
Folder structure
- WebsiteFolder -- Site1 --- app --- public --- tests --- writeable (.env, spark and other file) -- Site2 --- app --- public --- tests --- writeable (.env, spark and other file) -- shared/Models (DBSetting.php) -- system
Controller - Home.php
namespace App\Controllers; use shared\Models\DBSetting; class Home extends BaseController { public function index() { $db = new \shared\Models\DBSetting(); return view('welcome_message'); } }
Autoload.php
public $psr4 = [ APP_NAMESPACE => APPPATH, // For custom app namespace 'Config' => APPPATH . 'Config', 'shared\Models' => ROOTSOURCE . '/shared/Models' ];
Constants.php
define('ROOTSOURCE', dirname(__DIR__,3));
DBSetting.php
Namespace Sharing\Model; Using CodeIgniter\Model;
Class DBSetting extended model{
function __construct() { parent::__construct(); } public function save() { return true; }
}
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.