magento中Model创建以及该Model对于数据库的增删改查

时间:2023-03-09 05:09:13
magento中Model创建以及该Model对于数据库的增删改查

本文是按照magento英文文档照做与翻译的。

Model层的实现是mvc框架的一个巨大的部分。它代表了你的应用的数据,或者说大多数应用没有数据是无用的。Magento的Model扮演着一个重要的角色,就像他们有代表性地包含了业务逻辑,经常与controller或者helper方法有关在其他的php mvc框架中。

传统的php mvc models

如果MVC的定义有一点模糊的话,Model的定义也模糊。PHP开发者们优先广泛采用MVC模式,数据接入通常是原始的SQL语句或者是一个SQL抽象层。开发者们要写查询并且不用太多思考有关他们建造的模型对象。

如今,原生的SQL大多数是令人发愁的,但是许多PHP框架仍然是SQL为中心的,Models将是对象,这些对象提供一些抽象层,但是在前端场景开发者背后仍旧是写SQL并且称SQL像抽象方法去去读写他们的数据。

其他的框架避免SQL而且采用对象关系映射(ORM)的方法。在这里,一个开发者是严格处理对象,属性是设置的,当一个保存的方法被用于一个对象,数据就自动被写入数据库。一些ORM将尝试从数据库中预言对象属性,其他人要求用户去具体说明他们用一些方法(通常是一个抽象的数据语言YAML)。一个最著名的并且受欢迎的方法的实现是ActiveRecord。

这个ORM的定义应该能够为了现在,但是像每一个电脑科学在这些天,ORM的严格定义已经模糊了好些年,它超越了这个文章的范围去解决辩论,但是能够满足我们归纳它。

Magento Models

毫无疑问,magento采用了ORM方法,当zend framework SQL抽象是可以获得的,大多数的数据层都要经过建立在Magento Models中,并且你建立的Models,还因为magento高度灵活,高度抽象,这就是一个Model的概念。

剖析Magento的Model

大多数magento Models能够被分类在两个方法中的一个。那是一个基本的,类似ActiveRecord,一个对象一个标的Model,那还是一个Entity Attribute Value(EAV)实体属性值。每一个模型还会得到一个Model集合。集合是PHP对象们被用来去聚集许多个别的Magento Model实例。Magento团队已经实现了PHP标准库迭代器接口并且允许每一个Model类型可以去有他自己的集合类型。如果你对PHP的标准库不熟悉,可以理解为Model 集合成有很多方法的数组。

Magento Models没有包含任何代码去连接数据库。想反,每一个Model 用一个modelResource 类,它被用来去跟数据库服务连接(经由一个可读的,一个可写的适配器对象)。通过去耦,逻辑Model与和数据库连接的代码,理论上可以去写一个新的资源类为了不同的数据库模式与平台当保持你的模型不被触碰的时候。

Enable developer mode

有一些事情你应该做在开发中,但是绝不要在生产环境中,那就是开启magento的开发者模式,在你的浏览器中可以展示异常,对于调试你的代码还是有用的。

开启开发者模式的方法:

  • developer mode
  • Edit the .htaccess in the Magento root directory file to add SetEnv MAGE_IS_DEVELOPER_MODE "true"

创建一个基本的Model

我们先创建一个基本的magento Model,PHP MVC传统强调我们模拟一个网络日志发送,步骤如下:

  1. 创建一个“Weblog”模块
  2. 创建一个数据库的表为我们的模型
  3. 添加模型信息到配置文件 model名字叫Blogpost
  4. 添加Mddel 资源信息到配置文件为Blogpost模型
  5. 添加一个可读的适配器到配置文件为这个Blogpost模型
  6. 添加一个可写的适配器到配置文件为这个Blogpost模型
  7. 添加一个PHP的类文件为Blogpost模型
  8. 添加一个PHP类文件Blogpost资源模型

举例说明

1创建一个Weblog模块

In Magentotutorial/Weblog/etc/config.xml, setup the following route

 <frontend>
<routers>
<weblog>
<use>standard</use>
<args>
<module>Magentotutorial_Weblog</module>
<frontName>weblog</frontName>
</args>
</weblog>
</routers>
</frontend>

And then add the following Action Controller in

 class Magentotutorial_Weblog_IndexController extends Mage_Core_Controller_Front_Action {
public function testModelAction() {
echo 'Setup!';
}
}

at Magentotutorial/Weblog/controllers/IndexController.php. Clear your Magento cache and load the following URL to ensure everything's been setup correctly.

http://example.com/weblog/index/testModel

You should see the word "Setup" on a white background.

2.创建数据库的表

Magento有一个自动创建于改变数据库模型的系统,但是开始我们还是手动创建这个表为我们的Model。

CREATE TABLE `blog_posts` (
`blogpost_id` int(11) NOT NULL auto_increment,
`title` text,
`post` text,
`date` datetime default NULL,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`blogpost_id`)
)
INSERT INTO `blog_posts` VALUES (1,'My New Title','This is a blog post','2010-07-01 00:00:00','2010-07-02 23:12:30');

新建表并插入一行数据

3. The Global Config and Creating The Model    (Global的配置与创建模型)

有三个事情我们需要设置一个模型在我们配置文件

  1. 授权Models在我们的模块中
  2. 授权Model资源在我们的模块中
  3. 添加一个实体表配置在我们的模型资源中

当你实现了一个model在magento中,获取model的方法是

$model = Mage::getModel('weblog/blogpost');

GetModel的参数值第一部分就是得到Model组名。应该是module名字的小写或者是用包名+module名 (小写)。第二部分是Model名字的小写。

先加下面的配置信息在app\code\local\Magentotutorial\Weblog\etc\config.xml:

 <global>
<!-- ... -->
<models>
<weblog>
<class>Magentotutorial_Weblog_Model</class>
<!--
need to create our own resource, can't just
use core_resource
-->
<resourceModel>weblog_resource</resourceModel>
</weblog>
</models>
<!-- ... -->
</global>

<weblog /> tag is your Group Name,which should match your module name

<weblog />=====<magentotutorial_blog />
 <class /> is the BASE name all Models in the weblog group will have, also calles Class Prefix.前缀
The <resourceModel /> tag indicates which Resource Model that weblog group Models should use. There's more on this below, but for now be content to know it's your Group Name, followed by a the literal string "resource".
<resourceModel />参数就是Group Name_ resource
4. Create the following class at the following location
File: app/code/local/Magentotutorial/Weblog/Model/Blogpost.php
 class Magentotutorial_Weblog_Model_Blogpost extends Mage_Core_Model_Abstract
{
protected function _construct()
{
$this->_init('weblog/blogpost');
}
}

5.The Global Config and Resources

 <global>
<!-- ... -->
<models>
<!-- ... -->
<weblog_resource>
<class>Magentotutorial_Weblog_Model_Resource</class>
</weblog_resource>
</models>
</global>
 public function testModelAction() {
$params = $this->getRequest()->getParams();
$blogpost = Mage::getModel('weblog/blogpost');
echo("Loading the blogpost with an ID of ".$params['id']);
$blogpost->load($params['id']);
$data = $blogpost->getData();
var_dump($data);
}
http://example.com/weblog/index/testModel/id/1
6.资源类文件
File: app/code/local/Magentotutorial/Weblog/Model/Resource/Blogpost.php
 class Magentotutorial_Weblog_Model_Resource_Blogpost extends Mage_Core_Model_Resource_Db_Abstract{
protected function _construct()
{
$this->_init('weblog/blogpost', 'blogpost_id');
}
}

7.实体配置

   <models>
<!-- ... --->
<weblog_resource>
<class>Magentotutorial_Weblog_Model_Resource</class>
<entities>
<blogpost>
<table>blog_posts</table>
</blogpost>
</entities>
</weblog_resource>
</models>

结果:http://example.com/weblog/index/testModel/id/1

Loading the blogpost with an ID of 1

array
'blogpost_id' => string '1' (length=1)
'title' => string 'My New Title' (length=12)
'post' => string 'This is a blog post' (length=19)
'date' => string '2009-07-01 00:00:00' (length=19)
'timestamp' => string '2009-07-02 16:12:30' (length=19) 8.Basic Model Operations
$model->getData();
$model->getData('title');
$model->getOrigData();
$model->getOrigData('title');
$model->getBlogpostId();
$model->setBlogpostId(25);
$model->unsetBlogpostId();
if($model->hasBlogpostId()){...} 9.magento中的增删改查
$blogpost->load(1);(这个1就是数据库中主键那个1)
9.1插入
public function createNewPostAction() {
$blogpost = Mage::getModel('weblog/blogpost');
$blogpost->setTitle('Code Post!');
$blogpost->setPost('This post was created from code!');
$blogpost->save();
echo 'post with ID ' . $blogpost->getId() . ' created';
}
9.2修改
public function editFirstPostAction() {
$blogpost = Mage::getModel('weblog/blogpost');
$blogpost->load(1);
$blogpost->setTitle("The First post!");
$blogpost->save();
echo 'post edited';
}
9.3删除
public function deleteFirstPostAction() {
$blogpost = Mage::getModel('weblog/blogpost');
$blogpost->load(1);
$blogpost->delete();
echo 'post removed';
}
9.4查询(此时有多条数据,要有集合文件)
新建集合文件
app/code/local/Magentotutorial/Weblog/Model/Resource/Blogpost/Collection.php
 class Magentotutorial_Weblog_Model_Resource_Blogpost_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {
protected function _construct()
{
$this->_init('weblog/blogpost');
}
}
public function showAllBlogPostsAction() {
$posts = Mage::getModel('weblog/blogpost')->getCollection();
foreach($posts as $blogpost){
echo '<h3>'.$blogpost->getTitle().'</h3>';
echo nl2br($blogpost->getPost());
}
}
查询结果:

magento中Model创建以及该Model对于数据库的增删改查

数据库中的表:

magento中Model创建以及该Model对于数据库的增删改查