zoukankan      html  css  js  c++  java
  • 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    

     1 <frontend>
     2     <routers>
     3         <weblog>
     4             <use>standard</use>
     5             <args>
     6                 <module>Magentotutorial_Weblog</module>
     7                 <frontName>weblog</frontName>
     8             </args>
     9         </weblog>
    10     </routers>
    11 </frontend>

    And then add the following Action Controller in

    1 class Magentotutorial_Weblog_IndexController extends Mage_Core_Controller_Front_Action {
    2     public function testModelAction() {
    3         echo 'Setup!';
    4     }
    5 }

    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名字的小写。

    先加下面的配置信息在appcodelocalMagentotutorialWeblogetcconfig.xml:

     1 <global>
     2     <!-- ... -->
     3     <models>
     4         <weblog>
     5             <class>Magentotutorial_Weblog_Model</class>
     6             <!--
     7             need to create our own resource, can't just
     8             use core_resource
     9             -->
    10             <resourceModel>weblog_resource</resourceModel>
    11         </weblog>
    12     </models>
    13     <!-- ... -->
    14 </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
    1 class Magentotutorial_Weblog_Model_Blogpost extends Mage_Core_Model_Abstract
    2 {
    3     protected function _construct()
    4     {
    5         $this->_init('weblog/blogpost');
    6     }
    7 }

    5.The Global Config and Resources

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

    7.实体配置

     1   <models>
     2         <!-- ... --->
     3         <weblog_resource>
     4             <class>Magentotutorial_Weblog_Model_Resource</class>
     5             <entities>
     6                 <blogpost>
     7                     <table>blog_posts</table>
     8                 </blogpost>
     9             </entities>
    10         </weblog_resource>
    11     </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
    1 class Magentotutorial_Weblog_Model_Resource_Blogpost_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {
    2     protected function _construct()
    3     {
    4             $this->_init('weblog/blogpost');
    5     }
    6 }
    public function showAllBlogPostsAction() {
        $posts = Mage::getModel('weblog/blogpost')->getCollection();
        foreach($posts as $blogpost){
            echo '<h3>'.$blogpost->getTitle().'</h3>';
            echo nl2br($blogpost->getPost());
        }
    }
    查询结果:

    数据库中的表:

    
    
    
    
    
    


  • 相关阅读:
    前端百度地图开发使用总结
    换电脑后如何同步git本地仓库及分支
    vue mint-ui初次使用总结
    git学习入门总结
    深夜,当音乐响起,数据在MySQL中静静的疯狂计算
    且说Tomcat、Servlet、JSP和Spring
    国庆与中秋7天死磕Web的时光
    Android编程初涉,以控制摄像头为例
    谈现阶段如何形成可行的健康生活习惯方案
    说Java网络编程
  • 原文地址:https://www.cnblogs.com/baipeng/p/6625650.html
Copyright © 2011-2022 走看看