search
HomeBackend DevelopmentPHP TutorialMagento Development Notes 5_PHP Tutorial

Magento Development Notes 5_PHP Tutorial

Jul 14, 2016 am 10:07 AM
magentoDownensureSynchronizeandexisthowprojectdevelopfastdatabaseyesProductionofnotesIterate

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,...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.