Magento 코드를 변경, 확장 및 재작성 방법

19788 단어 agent
개발자인 당신은 반드시 Magento 코드를 바꾸어 당신의 업무 수요에 적응해야 합니다. 그러나 매우 많은 때에 우리는 Magento의 핵심 코드를 바꾸기를 원하지 않습니다. 여기에는 매우 많은 이유가 있습니다. 예를 들어 장래에 업그레이드Magento를 원하고 다른 Magento 코드를 많이 사용하고 싶습니다.만일 당신이 Magento 코드를 바꾸는 가장 좋은 방법을 찾고 있다면, 이 글은 좋은 강좌가 될 것입니다.
대상: 고급 개발자
목표에 적합: 개발자가 스스로 정의를 바꾸고 싶어하는 Magento
현재 버전: Magento versions: 1.4.0.1
저자: 정동

다시기 마젠토 모듈(Module)


첫 번째 단계는 본인의 코드에 속하는 명칭 공간을 만들어야 합니다. 예를 들어 MagentoNotes, 앱 등입니다. 여러분과 코드를 공유하기 편리하도록 저는 공간을 앱이라고 명명합니다.
app/
     code/
            core/
            community/
            local/
                    App/

만일 당신이 지금 Mage/Catalog/Block/Breadcrumbs를 바꾸려고 한다면.php 이 파일은 당신의 이름 공간에 앱에 새로운 모듈인'Catalog'를 추가할 수 있습니다.블록(Block) 폴더를 만들고 Breadcrumbs를 복사합니다.php를 새 폴더로 가져옵니다.여기에 config를 만들어야 합니다.xml 프로필.
app/
     code/
            core/
            community/
            local/
                    App/
                               Catalog/
                                          Block/
                                                 Breadcrumbs.php
                                          etc/
                                                 config.xml

Breadcrumbs 변경php의 클래스 이름은 App 입니다.Catalog_Block_Breadcrumbs, 원래의 이름인 Mage 계승Catalog_Block_Breadcrumbs.
이제 새 모듈을 활성화시켜야 마젠토가 새 모듈을 알 수 있습니다.
파일 app/etc/modules/App 만들기All.xml, 예를 들어 다음 코드를 추가합니다.
< ?xml version="1.0"?>
<config>
     <modules>
        <App_Catalog>
            <active>true</active>
            <codePool>local</codePool>
        </App_Catalog>
     </modules>
</config>

다음은Breadcrumbs를 복사하기 위한 특수한 라벨이 필요합니다. 다음은 모듈의 프로필을 통해 이루어집니다.

Blocks


파일 편집 "app/code/local/App/Catalog/etc/config.xml"
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <App_Catalog>
            <version>0.1.0</version>
        </App_Catalog>
    </modules>
    <global>
        <blocks>
            <catalog>
                <rewrite>
                        <breadcrumbs>App_Catalog_Block_Breadcrumbs</breadcrumbs>
                </rewrite>
            </catalog>
        </blocks>
    </global>
</config>

우리는 'Blocks' 라벨을 추가하거나, 이미 존재하는' Blocks' 라벨에 내용을 추가해야 한다.그리고 모듈 이름 뒤에 Rewrite 탭을 추가합니다. 이 예시에서 모듈 이름은'catalog'입니다.그리고 "breadcrumbs"라벨을 봅니다. 이 라벨은magento가 우리가 바꾸고 싶은 블록을 찾을 수 있도록 도와줍니다.우리 열에서breadcrumbs는Magento 핵심 코드의 클래스입니다: app/code/core/Mage/Catalog/Block/Breadcrumbs.php.만약 다른 폴더의 등급이 많다면, 하강선으로 구분할 수 있다.예를 들면 다음과 같습니다.
<blocks>
    <catalog>
        <rewrite>
                <category_view>App_Catalog_Block_Category_View</category_view>
        </rewrite>
    </catalog>
</blocks>

이 예시에서, 우리는 app/code/core/Mage/Catalog/Block/Category/View를 다시 썼다.php.
breadcrumbs 탭의 값은 클래스 이름입니다.Magento는 폴더 이름과 일치하기 때문에 클래스를 가져올 수 있습니다.zend 프레임워크를 사용한 사람들은 auto loader라는 물건을 자발적으로 불러오면 클래스 이름의 하강선과 폴더에 해당하는 클래스 파일을 불러올 수 있다는 것을 안다.한 가지 기억해라. 밑줄은 다음 단계의 폴더를 대표한다. 클래스 이름이 파일 폴더 이름과 일치하지 않는다면, Magento는 당신을 거들떠보지도 않을 것이다.예를 들면 다음과 같습니다.
1
2 App_Catalog_Block_Breadcrumbs → /app/code/local/App/Catalog/Block/Breadcrumbs.php App_Catalog_Block_Category_View → /app/code/local/App/Catalog/Block/Category/View.php

Controller - 정규 표현식 일치


다시 쓰기Magento 컨트롤러
1. 먼저 App에서 새로운 모듈을 만들고 다음과 같은 파일을 생성한다.
/app/code/local/App/Shopping
/app/code/local/App/Shopping/etc
/app/code/local/App/Shopping/etc/config.xml
/app/code/local/App/Shopping/controllers
/app/code/local/App/Shopping/controllers/CartController.php

2. 편집/app/code/local/App/Shopping/etc/config.xml 파일, 다음 코드 추가:
<?xml version="1.0"?>
<config>
    <modules>
        <App_Shopping>
            <version>0.1.0</version>
        </App_Shopping>
    </modules>
    <global>
        <!-- This rewrite rule could be added to the database instead -->
        <rewrite>
            <!-- This is an identifier for your rewrite that should be unique -->
            <!-- THIS IS THE CLASSNAME IN YOUR OWN CONTROLLER -->
            <App_Shopping_cart>
                <from><![CDATA[#^/checkout/cart/#]]></from>
                <!--
                    - Shopping module matches the router frontname below - checkout_cart
                    matches the path to your controller Considering the router below,
                    "/shopping/cart/" will be "translated" to
                    "/App/Shopping/controllers/CartController.php" (?)
                -->
                <to>/shopping/cart/</to>
            </App_Shopping_cart>
        </rewrite>
    </global>
    <!--
        If you want to overload an admin-controller this tag should be <admin>
        instead, or <adminhtml> if youre overloading such stuff (?)
    -->
    <frontend>
        <routers>
            <App_Shopping>
                <!-- should be set to "admin" when overloading admin stuff (?) -->
                <use>standard</use>
                <args>
                    <module>App_Shopping</module>
                    <!-- This is used when "catching" the rewrite above -->
                    <frontName>shopping</frontName>
                </args>
            </App_Shopping>
        </routers>
    </frontend>
</config>

3. 자신의 컨트롤러를 고쳐 쓴다
/app/code/local/App/Shopping/controllers/CartController.php
다음 코드를 컨트롤러에 추가하십시오. 우리가 유일하게 바꾸는 것은 index 동작에 error 를 추가하는 것입니다.log();
#            ,          ,     (Block)   
require_once 'Mage/Checkout/controllers/CartController.php';
class App_Shopping_CartController extends Mage_Checkout_CartController
{
    #  indexAction  
    public function indexAction()
    {
        # Just to make sure
        error_log('       !');
        parent::indexAction();
    }
}

이 코드에서 먼저 클래스 이름입니다. 앞에서 말한 블록(Block)과 같이 우리 자신의 클래스 이름은 App 입니다.Shopping_CartController가 원래 MageCheckout_CartController.indexAction에서 정보를 기록했습니다.
4、변경 AppAll.xml, 새 Shopping 모듈 활성화
<?xml version="1.0"?>
<config>
     <modules>
        <App_Catalog>
            <active>true</active>
            <codePool>local</codePool>
        </App_Catalog>
        <App_Shopping>
            <active>true</active>
            <codePool>local</codePool>
        </App_Shopping>
     </modules>
</config>

여기까지Magento 캐시 비우기 후, 당신은 이미 error 를 볼 수 있습니다log가 우리의 정보를 성공적으로 기록했습니다. 페이지magentonotes를 엽니다.com/checkout/cart/, 쇼핑 카트 페이지를 표시합니다. 모든 것이 정상적이지만,magentonotes에 방문하면 됩니다.com/shopping/cart/, 당신은 첫 페이지임을 발견할 수 있습니다...우리가 기대하는 카트 보기가 아직 나타나지 않았는데, 어떻게 해결합니까?우리 다음에 아래를 봅시다.
5, 보기 파일 변경 app/design/frontend/[myinterface]/[mytheme]/layout/checkout.xml은layout 탭에 다음과 같은 내용을 추가합니다.
<app_shopping_cart_index>
    <update handle="checkout_cart_index"/>
</app_shopping_cart_index>

주의해라, 이곳의 대문자와 소문자는 민감하다.
여기에서 기본적으로 큰 성과를 거두었지만, 나는 네가 정규 표현식을 배워야 한다고 건의한다. 왜냐하면 방금 코드에 이런 단락이 있기 때문이다.
1 < from >< ![CDATA[#^/checkout/cart/#]]></ from >
여기는 정규 표현식을 사용하여 일치하는 것입니다.
또한, 시도를 통해 여기는 같은 모듈 이름 덮어쓰기를 지원할 수 있습니다. 예를 들어Magento 코드의 상품 상세 정보 페이지는Mage 입니다.Catalog_Product Controller::view Action (), 이 Controller를 다시 쓰고 싶다면, 우리는 이렇게 할 수 있습니다: 1) 새 폴더/app/code/local/App/Catalog/controllers/Product Controller를 만듭니다.php 코드는 다음과 같습니다.
require_once 'Mage/Catalog/controllers/ProductController.php';
 
/**
 * Product controller
 *
 * @category   Mage
 * @package    Mage_Catalog
 */
class App_Catalog_ProductController extends Mage_Catalog_ProductController
{
    /**
     * View product action
     */
    public function viewAction()
    {
        echo '    ....';
        parent::viewAction();
    }
}

2) 편집/app/code/local/App/Catalog/etc/config.xml, 코드는 다음과 같습니다.
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <App_Catalog>
            <version>0.1.0</version>
        </App_Catalog>
    </modules>
    <global>
        <!-- This rewrite rule could be added to the database instead -->
        <rewrite>
            <!-- This is an identifier for your rewrite that should be unique -->
            <!-- THIS IS THE CLASSNAME IN YOUR OWN CONTROLLER -->
            <App_Shopping_cart>
                <from><![CDATA[#^/catalog/product/#]]></from>
                <!--
                    - Shopping module matches the router frontname below - checkout_cart
                    matches the path to your controller Considering the router below,
                    "/shopping/cart/" will be "translated" to
                    "/App/Shopping/controllers/CartController.php" (?)
                -->
                <to>/catalog/product/</to>
            </App_Shopping_cart>
        </rewrite>
        <blocks>
            <catalog>
                <rewrite>
                        <breadcrumbs>App_Catalog_Block_Breadcrumbs</breadcrumbs>
                </rewrite>
            </catalog>
        </blocks>
    </global>
    <frontend>
        <routers>
            <catalog>
                <use>standard</use>
                <args>
                    <module>App_Catalog</module>
                    <frontName>catalog</frontName>
                </args>
            </catalog>
        </routers>
    </frontend>
</config>

Magento 캐시 비우기
, 당신의 상품 상세 정보 페이지를 갱신해서 바뀌었는지 보세요, 허허.그러나 이런 방법은 폐단이 있다. 너는 반드시 이 모듈의 모든 Controller를 복사해야 한다. 그렇지 않으면 너는 비교적 큰 번거로움을 만날 것이다.여기까지 말하고 다시 쓰는 방법을 소개하겠습니다.
프로필 쓰기 방법을 자세히 보기:
<?xml version="1.0"?>
<config>
     <modules>
        <App_Mycms>
            <version>0.1.0</version>
        </App_Mycms>
    </modules>
    <frontend>
        <routers>
            <mycms>
                <use>standard</use>
                <args>
                    <module>App_Mycms</module>
                    <frontName>mycms</frontName>
                </args>
            </mycms>
        </routers>
    </frontend>
    <global>
        <routers>
            <cms>
                <rewrite>
                    <index>
                        <to>App_Mycms/index</to>
                        <override_actions>true</override_actions>
                        <actions>
                           <noroute><to>App_Mycms/index/noroute</to></noroute>
                        </actions>
                    </index>
                </rewrite>
            </cms>
        </routers>
    </global>
</config>

위에서 말한 바와 같이, 세 가지 재작성 방법은 모두 각기 천추가 있는데, 관건은 네가 어디에 쓰느냐에 달려 있다.또한 Magento는 기존 시스템의 모듈 이름과 일치하는 것을 권장하지 않는 것 같습니다. 예를 들어 MageCustomer는 이미 있습니다. 모듈의 이름은 Customer입니다. 만약 당신이 그것을 다시 쓰고 싶다면 App을 다시 만드는 것이 좋습니다.Customers 같은 거.

다시기 마젠토 모형 및 동작 도우미(Model &Helper)


우리가 Magento를 개작하는 과정에서 자신의 업무 논리를 실현하기 위해 그의 업무 모델을 바꾸는 것은 불가피하다.모듈 아래의 프로필로 클래스를 설정하고, 다시 쓰고 싶은 모델이나 조수를 계승해서 클래스를 호출할 수 있습니다.이제 우리는 사용자 모델을 예로 삼아 깊이 있게 설명한다.
1) 먼저 자체 모듈 디렉토리 만들기
app/code/local/App/Customer
app/code/local/App/Customer/etc/config.xml
app/code/local/App/Customer/Model
app/code/local/App/Customer/Model/Customer.php

2) 변경 app/etc/modules/AppAll.xml
<App_Customer>
    <active>true</active>
    <codePool>local</codePool>
</App_Customer>

3) 자체 모듈 프로필 변경 app/code/local/App/Customer/etc/config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <App_Customer>
            <version>0.1.0</version>
        </App_Customer>
    </modules>
 
    <global>
        <models>
            <customer>
                <rewrite>
                    <customer>App_Customer_Model_Customer</customer>
                </rewrite>
            </customer>
        </models>
    </global>
</config>

4) 파일 app/code/local/App/Customer/Model/Customer에 새 모델을 쓰십시오.php에서 새 클래스 AppCustomer_Model_Cutomer
class App_Customer_Model_Customer extends Mage_Customer_Model_Customer {
    //         
    public function validate() {
        // Define new validate rules. From now magento call this validate method instead of existing method
        //return $errors;
        return true;
    }
 
    //           
    public function newMethod() {
        // function logic
    }
}

5) 우리는 다시 한 종류를 써서 이해를 깊이 있게 한다.이제 Customer Address Model을 다시 작성합니다.Customer Model을 다시 쓰는 것과 같이 모듈의 프로필 app/code/local/App/Customer/etc/config를 편집합니다.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <App_Customer>
            <version>0.1.0</version>
        </App_Customer>
    </modules>
 
    <global>
        <models>
            <customer>
                <rewrite>
                    <customer>App_Customer_Model_Customer</customer>
                    <address>App_Customer_Model_Address</address>
                </rewrite>
            </customer>
        </models>
    </global>
</config>

위에서 보듯이, Rewrite 탭 안에 있는customer와address는 사실상 네가 복제하고자 하는magento 모델이다.
다음 모델 클래스 App 만들기Customer_Model_Address, 덮어쓰고 새로 고칠 방법을 쓰십시오.
class App_Customer_Model_Address extends Mage_Customer_Model_Address {
    //         
    public function validate() {
        // Define new validate rules. From now magento call this validate method instead of existing method
        //return $errors;
        return true;
    }
 
    //           
    public function newMethod() {
        // function logic
    }
}

6) Magento의 모형 자원을 어떻게 덮어쓰는지 다시 한 번 말씀드리겠습니다. 여기는Address Entity Modelclass를 복사하는 예를 들어 모듈의 프로필 app/code/local/App/Customer/etc/config를 변경하겠습니다.xml.
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <App_Customer>
            <version>0.1.0</version>
        </App_Customer>
    </modules>
 
    <global>
        <models>
            <customer>
                <rewrite>
                    <customer>App_Customer_Model_Customer</customer>
                    <address>App_Customer_Model_Address</address>
                </rewrite>
            </customer>
            <customer_entity>
                <rewrite>
                    <address>App_Customer_Model_Entity_Address</address>
                </rewrite>
            </customer_entity>
        </models>
    </global>
</config>

다음 클래스 파일 만들기
class App_Customer_Model_Entity_Address extends Mage_Customer_Model_Entity_Address {
    protected function _afterSave(Varien_Object $address) {
        // Write your code
    }
}

좋은 웹페이지 즐겨찾기