2012/08/21

PHP parse_url 不用再自己拆解URL了

曾經用過EXPLODE 和PREG_MATCH慢慢拆開URL...但原來有快方法parse_url


$url = "http://www.electrictoolbox.com/php-extract-domain-from-full-url/";
$parts = parse_url($url);

輸出:

Array
(
[scheme] => http
[host] => www.electrictoolbox.com
[path] => /php-extract-domain-from-full-url/
)


================================================================

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)

2012/08/10

改變地址次序等格式 Customer Address Format

因香港地區問題, 客人需要印出的PDF SLIP 中的姓名欄位根據特定格式展現:

E.G.   prefix LAST NAME , firstname

即是本來內置看成Mr Chris Wong 的, 要改成 Mr WONG , Chris

其實要分成兩部份去做

(1) 修改Address template
原來magento 已在backend提供了template 的XML

System->Configuration->Customer->Customers->Customer Configuration->Address Templates

改改排序就可以了 

{{depend prefix}}{{var prefix}} {{/depend}}{{var lastname}} {{depend middlename}}{{var middlename}}{{/depend}}, {{var firstname}}

這樣姓氏和名字的次序便倒轉了, 還可在中間加上逗號

(2)override observer "customer_address_format" 把姓氏轉為大寫

簡單先講做法:
config.xml 


<adminhtml>
<events>
            <customer_address_format>
                <observers>
                    <cleargo_custom>
                        <class>Cleargo_Custom_Model_Countryformat</class>
                        <method>countryFormat</method>
                    </cleargo_custom>
                </observers>
            </customer_address_format>
        </events>
    </adminhtml>

Cleargo/Custom/Model/Countryformat.php


class Cleargo_Custom_Model_Countryformat {
    public function countryFormat($observer) {
        $event = $observer->getEvent();
        $address = $event->getAddress();
        $type = $event->getType();
        //if($address->getData('country_id') == 'FR'){
            $lastname = strtoupper($address->getData('lastname'));
            $address->setData('lastname', $lastname);
        //}
    }
}
 



順便講講發現既過程

事源我要在PDF 裏更改格式, 於是在order/pdf/shipment.php 發現
$shippingAddress = $this->_formatAddress($order->getShippingAddress()->format('pdf'));

再追尋format這function 是源自Mage_Customer_Model_Address_Abstract

在入面可發現在render address前, dispatch了一個event
Mage::dispatchEvent('customer_address_format', array('type' => $formatType, 'address' => $this));

於是根據magento的dispatchEvent 機制, 我們可輕鬆override observer 以改變程式run到呢行時既data