Home > Backend Development > PHP Tutorial > Magento Development Notes 5_PHP Tutorial

Magento Development Notes 5_PHP Tutorial

WBOY
Release: 2016-07-14 10:07:28
Original
977 people have browsed it

In any rapidly iterative project, how to ensure synchronization of development and production (live network) databases is a headache. Magento provides a system for creating resource migration versions, which can help us deal with this problem that we constantly encounter during the development process. www.2cto.com

Last time we created the weblogpost model. This time, we execute CREATE TABLE directly. We will create a Setup Resource for our module, and this resource will create a table. We will also create an upgrade script that will upgrade the installed module. Overall
1. Add SetupResource in config
2. Create resourceclass file
3. Create installerscript
4. Create upgrade script
Add Setup Resource
We add the following
in the section
                                           
                                         
core_setup                
The
tag is used to uniquely represent SetupResource. The use of modelname_setup is generally encouraged. The Pachagename_Modulename of our module should be included under the XStarX_Weblog tag. Finally XStarX_Weblog_Model_Resource_Mysql4_Setup should contain the name of the Setup Resource class we want to create. For basic scripts, it's not necessary to create your own classes, but doing so will give you more flexibility later.
After adding the configuration, clear the cache and load Magento Site, you will find something abnormal
Fatalerror: Class 'XStarX_Weblog_Model_Resource_Mysql4_Setup' not found in
Magento tried to instantiate the class we declared in config, but it was not found. We need to create a class file like app/code/local/XStarX/Weblog/Model/Resource/Mysql4/Setup.php
classXStarX_Weblog_Model_Resource_Mysql4_Setup extendsMage_Core_Model_Resource_Setup { }
Now reload the Magento website and the exception will disappear.
Create installation script                                                                                  
Next, we want to create the installation script. The script contains the previous CREATETABLE statement.
First, take a look at config.xml
0.1.0
This part is necessary in the configuration file. It marks the module and also tells the version. The installation script should be based on the version. Create a file in the following location
app/code/local/XStarX/Weblog/sql/weblog_setup/mysql4-install-0.1.0.php
echo 'Running This Upgrade: '.get_class($this)."n
n";
die("Exit for now");
The weblog_setup part of the path matches the config.xml file . The 0.1.0 part matches the module version. Clear the cache, load the page, and you can see
Running This Upgrade:Alanstormdotcom_Weblog_Model_Resource_Mysql4_Setup Exit for now ...
This means our update script executed. Eventually we'll put the SQL update files here, but for now we'll focus on the setup mechanism. Remove the die statement,
echo 'Running This Upgrade:'.get_class($this)."n
n";
Reload the page and you can see the upgrade message displayed in the first part of the page. Reload and the page will return to normal. Because setup is only done once. It is impossible to always setup.
Create installation script
MagenoSetup Resources allows us to simply place installation scripts and upgrade scripts, and then the system will execute them automatically. This allows the data migration scripts in our system to be maintained once.
Use database client to view core_resroucetable
mysql> select * from core_resource;
+------------------------+---------+ |code                                                                                                                ---------------------+-----+
|adminnotification_setup | 1.0.0 |
| admin_setup | 0.7.1 |
| amazonpayments_setup | 0.1.2 |
| api_setup | 0.8.1 |
| backup_setup | 0.7.0 |
| bundle_setup | 0.1.7 |
| catalogindex_setup | 0.7.10 |
| cataloginventory_setup | 0.7.5 |
| catalogrule_setup | 0.7.7 |
| catalogsearch_setup | 0.7.6 |
| catalog_setup | 0.7.69 |
| checkout_setup | 0.9.3 |
| chronopay_setup | 0.1.0 |
| cms_setup | 0.7.8 |
| compiler_setup | 0.1.0 |
| contacts_setup | 0.8.0 |
| core_setup | 0.8.13 |
| cron_setup | 0.7.1 |
| customer_setup | 0.8.11 |
| cybermut_setup | 0.1.0 |
| cybersource_setup | 0.7.0 |
| dataflow_setup | 0.7.4 |
| directory_setup | 0.8.5 |
| downloadable_setup | 0.1.14 |
| eav_setup | 0.7.13 |
| eway_setup | 0.1.0 |
| flo2cash_setup | 0.1.1 |
| giftmessage_setup |0.7.2 |
| googleanalytics_setup | 0.1.0 |
| googlebase_setup | 0.1.1 |
| googlecheckout_setup | 0.7.3 |
| googleoptimizer_setup | 0.1.2 |
| ideal_setup | 0.1.0 |
| log_setup | 0.7.6 |
| newsletter_setup | 0.8.0 |
| oscommerce_setup | 0.8.10 |
| paybox_setup | 0.1.3 |
| paygate_setup | 0.7.0 |
| payment_setup | 0.7.0 |
 
| paypaluk_setup          | 0.7.0   |  
 
| paypal_setup            | 0.7.2   |  
 
| poll_setup              | 0.7.2   |  
 
| productalert_setup      | 0.7.2  |  
 
| protx_setup             | 0.1.0   |  
 
| rating_setup            | 0.7.2   |  
 
| reports_setup           | 0.7.7   |  
 
| review_setup            | 0.7.4   |  
 
| salesrule_setup         | 0.7.7   |  
 
| sales_setup             | 0.9.38  |  
 
| sendfriend_setup        | 0.7.2   |  
 
| shipping_setup          | 0.7.0   |  
 
| sitemap_setup           | 0.7.2   |  
 
| strikeiron_setup        | 0.9.1   |  
 
| tag_setup               | 0.7.2   |  
 
| tax_setup               | 0.7.8   |  
 
| usa_setup               | 0.7.0   | 
 
| weblog_setup            | 0.1.0   |  
 
| weee_setup              | 0.13    |  
 
| wishlist_setup          | 0.7.4   | 
 
 +-------------------------+---------+ 59 rowsin set (0.00 sec) 
 
这个表格包含了所有安装module的list,同时还有对应的版本。在表的结尾部分看到了
 
| weblog_setup            | 0.1.0   |  
 
这个就是Magento如何知道要不要重新执行脚本。如果都成功,页面就会加载。Weblog_setup已经安装了,所以不需要更新。如果想重装脚本,需要删除表里的改行。我们现在可以删除
 
DELETE from core_resource where code = 'weblog_setup';
 
然后删除对应的table
 
DROP TABLE blog_posts; 
 
接着在setup脚本里增加
 
$installer = $this; 
 
$installer->startSetup(); 
 
$installer->run("     
 
CREATE TABLE `{
 
$installer->getTable('weblog/blogpost')}`(       
 
`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`)     ) 
 
ENGINE=InnoDBDEFAULT CHARSET=utf8;      
 
INSERTINTO `{$installer->getTable('weblog/blogpost')}` VALUES (1,'My NewTitle','This is a blog post','2009-07-01 00:00:00','2009-07-02 23:12:30');         "); 
 
$installer->endSetup();
 
清除cache,加载页面,你可以看到blog_posts又创建了,并且有一条数据。
 
创建安装脚本---问题
上面的安装可能不会那么顺利,在magento1.7下面会报错
 
Mage_Eav_Exception: Can't create table: module_entity
 
 
如何解决呢?
 
Debug createEntityTables()方法,可以在结尾处看到
 
$connection->beginTransaction(); try {      foreach ($tables as $tableName => $table) {         $connection->createTable($table);     }     $connection->commit(); } catch (Exception $e) {    Zend_Debug::dump($e->getMessage());    $connection->rollBack();    throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Can't create table: %s', $tableName)); }
 
 
查看底层错误是:UserError: DDL statements are not allowed in transactions
 
然后跟进commit函数
 
/** * Check transaction level in case of DDL query  *  * @param string|Zend_Db_Select $sql  * @throws Zend_Db_Adapter_Exception  */ protected function _checkDdlTransaction($sql) {     if (is_string($sql) && $this->getTransactionLevel() > 0) {         $startSql = strtolower(substr(ltrim($sql), 0, 3));         if (in_array($startSql, $this->_ddlRoutines)) {             trigger_error(Varien_Db_Adapter_Interface::ERROR_DDL_MESSAGE, E_USER_ERROR);         }     } }
 
结论是Mysql不支持DDL Transaction。
 
因此在app/code/local/{CompanyName}/{ModuleName}/Setup/Helper.php里重写createEntityTable方法
 
{         ...           /**         * Remove transaction code due to issues with errors.          */         //$connection->beginTransaction();         try {              foreach ($tables as $tableName => $table) {                 $connection->createTable($table);             }             $connection->commit();        } catch (Exception $e) {            //$connection->rollBack();            throw Mage::exception('Mage_Eav', Mage::helper('eav')->__('Can't create table: %s', $tableName));        }     } }
 
 
然后问题解决。
 
Setup脚本剖析
让我们一行一行的解释。首先
 
$installer = $this; 
 
每个安装脚本都是从SetResource类开始执行的(就是我们上面创建的)。这意味着脚本中的$this引用是这个类实例化的引用。如果不是必须,core系统里大部分安装脚本都是把$this命名未installer,此处我们也是这样。
 
接下来我们看到了两个方法
 
$installer->startSetup(); 
 
//... 
 
$installer->endSetup(); 
 
如果查看Mage_Core_Model_Resource_Setup类(在目录app/code/core/Mage/Core/Resource/Setup.php),你可以看到如下的内容
 
public function startSetup()     
 
{      
 
        $this->_conn->multi_query("
 
                          SET SQL_MODE=''; 
 
                          SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; 
 
                          SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'; ");          
 
         return $this;     
 
}      
 
public function endSetup()    
 
 {
 
         $this->_conn->multi_query(" 
 
              SET SQL_MODE=IFNULL(@OLD_SQL_MODE,'');
 
              SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS,0); ");         
return $this;
}
Finally we execute
$installer->run(...);
This accepts a SQL containing the creation of a database. You can define arbitrary queries, just separate them with semicolons. At the same time, please also pay attention
$installer->getTable('weblog/blogpost')
The getTable method allows us to pass in the Magento Model URI and then get its table name. If it is not necessary, use this method. The Mage_Core_Model_Resource_Setup class contains many useful Helper methods. The most effective way to learn is to study the installer scripts of Magento core.
Module upgrade
The above describes how to initialize the data table, but how to change the structure of the existing ink fragrance? Magento's Setup Resources supports a simple version strategy that allows us to automatically execute scripts to upgrade our modules.
Once Magento executes an installation script, it will not execute another installation script again. At this time, we should create an upgrade script. The upgrade script is very similar to the installation script, with some key differences.
To start, we create a script in the following location,
XStarX/Weblog/sql/weblog_setup/mysql4-upgrade-0.1.0-0.2.0.php
echo 'Testing our upgrade script (mysql4-upgrade-0.1.0-0.2.0.php) and halting execution to avoid updating the system version number
';
die();
The upgrade script and the installation script are in the same directory, but slightly different. First, the file name must contain upgrade. Secondly, there must be two version numbers separated by "-". The first is the source version of the upgrade, and the second is the target version of the upgrade.
After clearing the cache, the page is reloaded, but the script is not executed at this time. We need to update the version information in config.xml to trigger the upgrade
                                                                                                                             
                                                                                                                                          
                                                                                                           
After writing the new version number, if you clear the cache and load the website, you can see the output. There is another key point that needs attention at this time, so don’t rush to do this step. We create another file in the same directory
XStarX/Weblog/sql/weblog_setup/mysql4-upgrade-0.1.0-0.1.5.php
echo 'Testing our upgrade script (mysql4-upgrade-0.1.0-0.1.5.php) and NOT halting execution
';
At this time, clear the cache and load the page, and you can see two pieces of information. When Magento discovers that the version number information has changed, it will execute all executable scripts to update the module. Even though we never created the 0.1.5 version, Magento sees the upgrade script and tries to execute it. Scripts are generally executed in order from low to high. The data below will illustrate this
mysql> select * from core_resource where code = 'weblog_setup'; +-------------+---------+
| code | version | +--------------+---------+
| weblog_setup | 0.1.5 | +--------------+---------+
1 row in set (0.00 sec)
We see that the version in the data sheet is 1.5. This is because we upgraded from 1.0 to 1.5, but did not perform the upgrade from 1.0 to 2.0. Okay, after explaining this key issue, let’s get back to business. Back to the script, first modify the upgrade script 0.1.0-0.2.0
$installer = $this;
$installer->startSetup();
$installer->run("
ALTER TABLE `{$installer->getTable('weblog/blogpost')}`
CHANGE post post text not null; ");
$installer->endSetup();
die("You'll see why this is here in a second");
Refresh the page, but nothing happens. Why is the upgrade script not executed?
1. weblog_setup resource is version 0.1.0
2. We want to upgrade the module to 0.2.0
3. Magento sees the upgrade module and there are two scripts to execute, 0.1.0-0.1.5 and 0.1.0-0.2.0
4. Magento loads the queue and then executes
5. Magento executes scripts from 0.1.0 to 0.1.5
6. Weblog_setup resource is now 0.1.5
7. Magento executes the scripts from 0.1.0 to 0.2.0 and execution stops
8. When the next page is loaded, Magento sees that weblog_set is in version 0.1.5, but does not see any scripts executed starting from 0.1.5 (the previous ones started from 0.1.0)
The correct way is as follows, rename the file
mysql4-upgrade-0.1.0-0.1.5.php #This goes from 0.1.0 to 0.1.5
mysql4-upgrade-0.1.5-0.2.0.php #This goes 0.1.5 to 0.2.0
Magento is able to complete two upgrades once loaded. You can clear the core_resource table information to complete the final test
update core_resource set version = '0.1.0' where code = 'weblog_setup';
Magento performs upgrades based on configuration files, so pay attention to adding scripts during collaborative development.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477854.htmlTechArticleIn any rapidly iterative project, how to ensure the synchronization of development and production (live network) databases is a headache things. Magento provides a system for creating migrated versions of resources,...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template