您的代码似乎最适合与 DataMapper ORM 和 CodeIgniter 一起使用。
稍微解释一下,DataMapper 只是一个抽象层。在使用数据库并将对象映射到表时,它可以处理许多必需品。话虽如此,您不必加载模型等。只要您自动加载数据库库和 datamapper 库,就可以使用 DataMapper。
验证数组让 DataMapper 知道对您的属性的要求。因此,如果您尝试保存对象并且您创建/更改的属性之一不满足这些要求,那么您的保存将失败并且您将收到一条错误消息:
// For example
if ($myObj->save())
{
// $myObj validation passed and is saved to db
}
else
{
// $myObj validation failed, save did not complete
echo $myObj->error->string;
}
Codeigniter 已经有一个名为 的库Cart
,因此您不想命名您的模型Cart
。因此,您可以将该模型重命名为Basket
或其他有意义的名称。
我知道您仍然只是想让事情正常进行,但我觉得您需要稍微考虑一下您的数据结构。您不会将 保存username
在Cart
对象中,这就是我们使用关系的原因。所以,我会像这样构造它:
// baskets table (a table represents many baskets, therefore it is plural)
id
user_id
blah
blah
created
updated
// users table
id
username
email_address
created
updated
// basket model (a model represents 1 basket, therefore it is singular)
class Basket extends DataMapper
{
public function __construct()
{
parent::__construct();
}
var $has_one = array('user'); // each basket belongs to one user
var $validation = array(...);
}
// user model
class User extends DataMapper
{
public function __construct()
{
parent::__construct();
}
var $has_many = array('basket'); // each user can have many baskets
var $validation = array(...);
}
// controller
public function __construct()
{
parent::__construct();
}
public function index()
{
$basket = new Basket();
$basket->blah = 'whatever';
$basket->save();
// at this point, $basket is saved to the database
// now let's add it to the user
$user = new User();
$user->where('id', 1)->get(1);
// now we have a user
// save the relationship to the basket
$user->save($basket);
// now $basket->user_id == 1
// get the username from the basket
$u = $basket->user->get();
$username = $u->username;
// yes, there are faster and shorter ways to write most of this,
// but I think for beginners, this syntax is easier to understand
}