Magento Development notes 5

Source: Internet
Author: User
Tags magento website

In any fast iteration project, it is a headache to ensure the synchronization of development and production (current network) databases. Magento provides a system for creating resource migration versions, which can help us deal with this problem that is constantly encountered during the development process. Www.2cto.com we created the weblogpost model last time. This time, we execute create table directly. We will not create a Setup Resource for our module, and this Resource will create a table. We will also create an upgrade script to upgrade the installed module. In general, 1. add SetupResource 2 in config. create the resourceclass file 3. create installerscript 4. create and upgrade script and add Setup Resource. In the <resource/> section, add the following <resources> <! --... --> <Weblog_setup> <setup> <module> XStarX_Weblog </module> <class> XStarX_Weblog_Model_Resource_Mysql4_Setup </class> </setup> <connection> <use> core_setup </use> </connection> </weblog_setup> <! The --... --> </resources> <weblog_setup> label is used to uniquely represent SetupResource. Modelname_setup is generally encouraged. The <module> XStarX_Weblog </modul> label should contain the Pachagename_Modulename of our module. The last <class> XStarX_Weblog_Model_Resource_Mysql4_Setup </class> should contain the name of the Setup Resource class we want to create. For basic scripts, there is no need to create your own classes, but this can be more flexible in the future. After adding the configuration, clear the cache and load the Magento Site. You will find the Fatalerror: class 'xstarx _ Weblog_Model_Resource_Mysql4_Setup 'not found in Magento tries to instantiate the Class we declare in config, but it cannot be found. We need to create such a class file app/code/local/XStarX/Weblog/Model/Resource/Mysql4/Setup. php classXStarX_Weblog_Model_Resource_Mysql4_Setup extendsMage_Core_Model_Resource_Setup {} Now reloads the Magento website, and the exception disappears. Create an installation script. Next, create an installation script. The script contains the previous CREATETABLE statement. First, let's take a look at config. xml <modules> <XStarX_Weblog> <version> 0.1.0 </version> </XStarx_Weblog> </modules> is required in the configuration file, the module version is also indicated. The installation script must be based on the version. Create the file app/code/local/XStarX/Weblog/SQL/weblog_setup/mysql4-install-0.1.0.php echo 'running This Upgrade :'. get_class ($ this ). "\ n <br/> \ n"; die ("Exit for now"); The weblog_setup part of the path matches config. xml file <weblog_setup/>. The 0.1.0 part matches the module version. Clear the cache and load the page. You can see Running This Upgrade: Alanstormdotcom_Weblog_Model_Resource_Mysql4_Setup Exit for now... This means that our update script is executed. In the end, we put the SQL Update file here, but now we focus on the setup mechanism. Remove the die declaration and echo 'running This Upgrade :'. get_class ($ this ). "\ n <br/> \ n"; reload the page to display the upgrade message in the first part of the page. Reload, the page will return to normal. Because setup is the same. It is impossible to always set up. The create installation script MagenoSetup Resources allows us to simply place the installation script and upgrade script, and then the system will automatically execute it. This allows the data migration script in our system to be retained once. Use the database client to view core_resroucetable mysql> select * from core_resource; + versions + --------- + | code | version | + versions + ----- + | 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 | cat Latency | 0.7.7 | latency | 0.7.6 | catalog_setup | 0.7.69 | latency | 0.9.3 | chronopay_setup | 0.1.0 | cms_setup | 0.7.8 | latency | 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 | Connecticut | 0.1.1 | Connecticut | 0.7.2 | googleanalytics_setup | 0.1.0 | googlebase_setup | 0.1.1 | 2.16| 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 | pa Ygate_setup | 0.7.0 | payment_setup | 0.7.0 | telephone | 0.7.0 | paypal_setup | 0.7.2 | poll_setup | 0.7.2 | telephone | 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 | strikeiro | 0.7.2 | N_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 | + detail + --------- + 59 rowsin set (0.00 sec) this table contains the list of all installed modules and corresponding versions. In the end of the table, we can see | weblog_setup | 0.1.0 | This Is How Magento knows whether to re-execute the script. If both are successful, the page will be loaded. Weblog_setup has been installed, so you do not need to update it. To reinstall the script, you need to delete the rows in the table. Now we can DELETE from core_resource where code = 'weblog _ setup'; then DELETE the corresponding table drop table blog_posts; then add $ installer = $ this in the setup script; $ 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', '2017-07-01 00:00:00 ', '2017-07-02 23:12:30 ');"); $ installer-> endSetup (); clear the cache and load the page. You can see that blog_posts has been created and there is a data record. Create installation script-the above installation may not be so smooth. Mage_Eav_Exception: Can't create table: module_entity will be reported in magento1.7. How Can this problem be solved? Debug createEntityTables () method. You can see $ connection-> beginTransaction () at the end; 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);} Check the underlying error: UserError: DDL statements Are not allowed in transactions and then follow up the commit function/*** 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) ;}} the conclusion is that Mysql does not support DDL Transaction. Therefore, in app/code/local/{CompanyName}/{ModuleName}/Setup/Helper. rewrite the createEntityTable method in php {... /*** 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) ;}}then the problem is solved. The Setup script profiling allows us to explain one line at a time. First, $ installer = $ this; each installation script is executed from the SetResource class (that is, the one we created above ). This means that the $ this reference in the script is a reference to the class instantiation. If it is not necessary, most of the installation scripts in the core system name $ this without installer. this is also the case here. Next we see two methods: $ installer-> startSetup ();//... $ installer-> endSetup (); If you view the Mage_Core_Model_Resource_Setup class (in the app/code/core/Mage/Core/Resource/Setup directory. php), you can see the following 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;} publi C 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, run $ installer-> run (...); this accepts an SQL statement that includes creating a database. You can define any query, separated by semicolons. At the same time, note that the $ installer-> getTable ('weblog/blogpost') getTable method allows us to pass in the Magento Model URI and obtain its table name. If not necessary, use the following method for execution. The Mage_Core_Model_Resource_Setup class contains many useful Helper methods. The most effective learning is to study the Magento core installer scripts. Module upgrade describes how to initialize a data table, but how to change the existing structure of Mo Xiang? Magento's Setup Resources supports a simple version policy 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, except for some key points. As a start, we create a script in the following locations, 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 <br/> '; die (); the upgrade script and installation script are in the same directory, but slightly different. First, the file name must contain upgrade. Second, there must be two versions separated. The first is the source version of the upgrade, and the second is the target version of the upgrade. After the cache is cleared, the page is reloaded, but the script is not executed at this time. We need to update config. to trigger the upgrade <modules> <Alanstormdotcom_Weblog> <version> 0.2.0 </version> </Alanstormdotcom_Weblog> </modules> after the new version number is written, if the cache is cleared, load the website and you will see the output. At this time, there is another key point to be aware of, so do not panic to do this step first. We create another file 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 'in the same directory '; in this case, clear the cache and load the page. You can see two messages. When Magento finds that the version number is changed, it will execute all executable scripts to update the module. Although we have never created version 0.1.5, Magento will see the upgrade script and then try to execute it. Generally, scripts are executed in ascending order. The following data shows the mysql> select * from core_resource where code = 'weblog _ setup '; + -------------- + --------- + | code | version | + -------------- + --------- + | weblog_setup | 0.1.5 | + -------------- + --------- + 1 row in set (0.00 sec) the data table version 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. Now, let's get down to the point. Return to the script and 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 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. There are two scripts to execute, 0.1.0-0.1.5 and 0.1.0-0.2.0 4. magento load the queue, and then execute 5. magento executes script 0.1.0 to 0.1.5 6. weblog_setup resource is 0.1.5 now 7. magento executes the script 0.1.0 to 0.2.0 and stops the script 8. when loading the next page, Magento sees that weblog_set is in version 0.1.5, but does not see any script executed starting from 0.1.5 (earlier than 0.1.0). The correct method is as follows, renaming 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.p Hp # This goes 0.1.5 to 0.2.0 Magento is capable of loading two upgrades at a time. 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 is upgraded Based on the configuration file. Therefore, you must pay attention to adding scripts during collaborative development.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.