tÀi liỆu hƯỚng viẾt module vÀ webservice cho magento 1.7

16
TÀI LIỆU HƯỚNG VIT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7 Tài liu kthut 06/2012

Upload: dvms

Post on 25-Dec-2014

1.313 views

Category:

Technology


4 download

DESCRIPTION

TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

TRANSCRIPT

Page 1: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

TÀI LIỆU HƯỚNG VIẾT MODULE VÀ

WEBSERVICE CHO MAGENTO 1.7

Tài liệu kỹ thuật

06/2012

Page 2: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 2 /16

Lịch sử chỉnh sửa

Ngày tháng Version Mô tả Người viết

06/2012 1.7 DVMS

Page 3: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 3 /16

MỤC LỤC

Page 4: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 4 /16

1. Tạo module:

Một module sẽ bao gồm một trong các thành phần sau :

Settings

Database schemas

Rendering objects

Utility helpers

Data models

Action controllers

Các module có thể được xác định là ON hay OFF thông qua file XML configuration tại thư mục

app/etc/modules/ directory. Mỗi module có file config cuar riêng nó tại thư mục etc/

Cài đặt Module creator extension: Vào link sau để download Module creator về:

http://www.magentocommerce.com/wiki/_media/modulecreator0.0.9.1.zip

=> Giải nén vào thu mục chứa source Magento ta được thư mục "moduleCreator".

=> Tiếp đến mở trình duyệt lên và chạy link: http://www.your_site.com/moduleCreator/index.php

sẽ thấy giao diện giống như bên dưới:

Page 5: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 5 /16

=> nhập các thông tin về module của bạnVà trong folder code sẽ sinh ra thư mục

[root]/moduleCreator

Chú ý: phần "Magento Root Directory" nếu không nhập gì -> thì code sẽ được tạo trong

[root]/moduleCreator/new.

Dựa vào giao diện này sẽ điền thông tin để tạo ra module News (điền thông tin Namespace: Packt,

Module: News , Design: default, Design: default - phần này code design sẽ nằm trong folder

default/default)

=> nhấn Create để tạo. Lúc này một loạt folder được sinh ra giống như hình bên dưới:

=> Sau khi tạo xong bạn vào copy toàn bộ source mới tạo ra trong thư mục: “new/app “ vào thư

mục app của Magento.

Khi đó trong giao diện admin ta sẽ thấy có một menu mới => click vào menu này ta sẽ có giao diện

cơ bản như sau:

Page 6: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 6 /16

=> Bây giờ giải quyết trọng tâm chính là Controller. Controller giữ vai trò trọng tâm ở đây, nó có

nhiệm vụ chính là map một URL với function xử lý logic cho nó. Vào folder "app/code/local/ tên

Namespace mới tạo/tên module mới tạo/controllers" edit file IndexController.php" để thay đổi logic

business của nó.

Ví dụ: module tôi tạo có Namespace là: “NguyenLinh” và tên module là: “Example” thì tôi vào sửa

file: app/code/local/NguyenLinh/Example/controllers/IndexController.php

Nếu bạn muốn tạo module bằng tay mà không dùng module Creator thì có thể tham khảo cách làm

tại link sau:

http://www.webspeaks.in/2010/08/create-your-first-adminbackend-module.html

http://www.webspeaks.in/2010/07/create-your-first-magento-module.html

2. Tạo thêm webservice:

- Cấu trúc cơ bản của một module API như sau:

app/code/

|- community/ or local/ or core/

| |- COMPANYNAME/

| |- MODULENAME/

| |- etc/

| |- api.xml

| |- config.xml

| |- Helper/

Page 7: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 7 /16

| |- Data.php

| |- Model/

| |- OBJECT1/

| |- Api.php

| |- Object2/

| |- Api.php

|- etc/modules/

|- COMPANYNAME_MODULE.xml

- ví dụ tôi tạo API danh sách các sản phẩm bán chạy, cấu trúc module của tôi như sau:

app/

|- code/community/

| |- GrelaDesign/

| |- Tutorial/

| |- etc/

| |- api.xml

| |- config.xml

| |- Helper/

| |- Data.php

| |- Model/

| |- Core/

| |- Api.php

| |- DashBoard/

| |- Api.php

|- etc/modules/

|- GrelaDesign_Tutorial.xml

- GrelaDesign_Tutorial.xml: Tập tin này chỉ thị cho Magento tìm thấy API

<!-- GrelaDesign_Tutorial.xml -->

<config>

<modules>

<GrelaDesign_Tutorial>

<active>true</active>

<codePool>community</codePool><!-- this could be also 'local' -->

<depends>

<Mage_Api />

</depends>

</GrelaDesign_Tutorial>

</modules>

</config>

- config.xml: tập tin cấu hình module:

<!-- config.xml -->

Page 8: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 8 /16

<config>

<modules>

<GrelaDesign_Tutorial><!-- COMPANYNAME_MODULE -->

<version>0.0.0.1</version>

</GrelaDesign_Tutorial>

</modules>

<global>

<models>

<tutorial><!-- MODULE, just first letter is lowercased, i.e. module

CustomAPI would be placed here as customAPI -->

<class>GrelaDesign_Tutorial_Model</class>

</tutorial>

</models>

<helpers>

<tutorial>

<class>GrelaDesign_Tutorial_Helper</class>

</tutorial>

</helpers>

</global>

</config>

Trong hướng dẫn này, sẽ tạo ra ba phương thức cho API. Đầu tiên sẽ là getVersion trong Core, thứ hai sẽ là

getBestsellers và getTotals thứ ba cũng có trong DashBoard.

Trong ví dụ này sẽ có 2 nhóm truy cập: "allaccess" và "owneracess".

<!-- api.xml -->

<config>

<api>

<resources>

<tutorial_core translate="title" module="tutorial">

<title>GrelaDesign tutorial Core API calls</title>

Page 9: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 9 /16

<model>tutorial/core_api</model>

<acl>greladesign/tutorial</acl>

<methods>

<getVersion translate="title" module="tutorial">

<title>Returns version of this API</title>

<acl>greladesign/tutorial/allaccess</acl>

</getVersion>

</methods>

</tutorial_core>

<tutorial_dashboard translate="title" module="tutorial">

<title>GrelaDesign tutorial DashBoard app API calls</title>

<model>tutorial/dashBoard_api</model>

<acl>greladesign/tutorial</acl>

<methods>

<getSalesTotals translate="title" module="tutorial">

<title>Get sales totals</title>

<method>getTotals</method><!-- here we specify the

method name if we have a conflict with built in method or we want to change the name i.e. because

it is lengthy -->

<acl>greladesign/tutorial/owneraccess</acl>

</getSalesTotals>

<getBestsellers translate="title" module="tutorial">

<title>Get best selling product list</title>

<acl>greladesign/tutorial/allaccess</acl>

</getBestsellers>

</methods>

</tutorial_dashboard>

</resources>

Page 10: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 10 /16

<resources_alias><!-- here we can put aliases, shortened calls for our api resource, I

haven't checked how alias behaves when it collides with different resource... -->

<dashboard>tutorial_dashboard</dashboard>

<core>tutorial_core</core>

</resources_alias>

<acl><!-- Access Control List to our resources, this tree structure is displayed in

"Resource Roles" panel when you open role to edit -->

<resources>

<greladesign translate="title" module="tutorial">

<title>GrelaDesign</title>

<sort_order>100</sort_order>

<tutorial translate="title" module="tutorial">

<title>Tutorial</title>

<sort_order>100</sort_order>

<allaccess translate="title" module="tutorial">

<title>Core functionality required by all

users.</title>

<sort_order>10</sort_order>

</allaccess>

<owneraccess translate="title" module="tutorial">

<title>Functions accessible only for

owner.</title>

<sort_order>50</sort_order>

</owneraccess>

</tutorial>

</greladesign>

</resources>

</acl>

</api>

Page 11: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 11 /16

</config>

<!-- app/code/community/GrelaDesign/Tutorial/Model/Core/Api.php -->

<?php

class GrelaDesign_Tutorial_Model_Core_Api

{

/**

* Returns version of the installed magento

* @return String

*/

public function getVersion()

{

return Mage::getVersion();

}

}

?>

<!-- app/code/community/GrelaDesign/Tutorial/Model/Core/Api.php -->

<?php

class GrelaDesign_Tutorial_Model_Core_Api

{

/**

* Returns version of the installed magento

* @return String

*/

public function getVersion()

{

return Mage::getVersion();

Page 12: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 12 /16

}

}

?>

<!-- app/code/community/GrelaDesign/Tutorial/Model/DashBoard/Api.php -->

<?php

class GrelaDesign_Tutorial_Model_DashBoard_Api

{

/**

* Returns list of best selling products, returned list is limited to the number items specified

in argument.

* @param int $limit

*/

public function getBestsellers($limit=5)

{

//filter

$visibility = array(

Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,

Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG

);

$_arrayOfBestsellers = Mage::getResourceModel('reports/product_collection')

->addAttributeToSelect('*')

->addOrderedQty()

-

>addAttributeToFilter('visibility', $visibility)

->setOrder('ordered_qty', 'desc')

->getSelect()->limit($limit)-

>query();

$bestProducts = array();

$details = Mage::getModel('catalog/product');

foreach ($_arrayOfBestsellers as $product)

{

$details->load($product['entity_id']);

$bestProduct[] = array(

"qty" => $product["ordered_qty"]

, "price" => $details->getPrice()

, "name" => $details->getName()

);

}

return $bestProduct;

}

Page 13: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 13 /16

/**

* Get sales totals

* Returns totals for : Revenue, Tax, Shipping and Quantity for given time range, default is

last 24 hours.

* @param String $period - default '24h', possible values are: 24h, ,1y, 2y

*/

public function getTotals($period='24h')

{

$collection = Mage::getResourceModel('reports/order_collection')

->addCreateAtPeriodFilter($period)

//->getSelectCountSql()

->calculateTotals(1)

;

/*

$collection->addFieldToFilter('store_id',

array('eq' => Mage::app()-

>getStore(Mage_Core_Model_Store::ADMIN_CODE)->getId())

);

*/

$collection->load();

$totals = $collection->getFirstItem();

return array(

'Revenue' => $totals->getRevenue()

, 'Tax' => $totals->getTax()

, 'Shipping' => $totals->getShipping()

, 'Quantity' => $totals->getQuantity() * 1

);

}

}

?>

<!-- app/code/community/GrelaDesign/Tutorial/Helper/Data.php -->

<?php

class GrelaDesign_Tutorial_Helper_Data extends Mage_Core_Helper_Abstract

{

}

?>

- giờ ta vào admin của website và tạo ra các user để test thử API

Page 14: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 14 /16

rule: “owner”

user: admin

pass: 1admin

rule: “client”

user: johndoe

pass: j0hn

- Tạo ra tập tin test có nội dung như sau:

<?php

/*

Create a file called, 'test.php' in the root of your Magento development environment.

Copy the code below into your test.php file.

Browse to http://yourstore/test.php.

*/

// Tell this file to use the Mage libraries

$mageFilename = 'app/Mage.php';

require_once $mageFilename;

umask(0);

// Note we are using the 'app' directive not the 'run' directive here

// Also note the store is named 'default' by, well, default. But as Zeke pointed out if your store is

// 'en' then you would need to edit the following line to say Mage::app('en')

// Let's go with 'default' for simplicity ...

Mage::app('default');

// Your test code goes here

echo "<pre>";

$client = new Zend_XmlRpc_Client('http://127.0.0.1/magento/api/xmlrpc/');

Page 15: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 15 /16

// If some stuff requires api authentication,

// we should get session token

//login

$session = $client->call('login', array('admin', '1admin'));

echo var_dump($client->call('call', array($session, 'tutorial_dashboard.getBestsellers'))), "\n";

echo var_dump($client->call('call', array($session, 'dashboard.getBestsellers'))), "\n";

echo var_dump($client->call('call', array($session, 'tutorial_dashboard.getSalesTotals'))), "\n";

echo var_dump($client->call('call', array($session, 'dashboard.getSalesTotals'))), "\n";

echo var_dump($client->call('call', array($session, 'tutorial_core.getVersion'))), "\n";

echo var_dump($client->call('call', array($session, 'core.getVersion'))), "\n";

//logout

echo $client->call('endSession', array($session)), "\n";

//login

$session = $client->call('login', array('johndoe', 'j0hn'));

echo var_dump($client->call('call', array($session, 'tutorial_dashboard.getBestsellers'))), "\n";

echo var_dump($client->call('call', array($session, 'dashboard.getBestsellers'))), "\n";

try {

//this will throw an exception ("access denied")

echo var_dump($client->call('call', array($session, 'tutorial_dashboard.getSalesTotals'))),

"\n";

echo var_dump($client->call('call', array($session, 'dashboard.getSalesTotals'))), "\n";

} catch (Exception $e) {

echo $e->getMessage(), "\n";

}

Page 16: TÀI LIỆU HƯỚNG VIẾT MODULE VÀ WEBSERVICE CHO MAGENTO 1.7

Trang 16 /16

echo var_dump($client->call('call', array($session, 'tutorial_core.getVersion'))), "\n";

echo var_dump($client->call('call', array($session, 'core.getVersion'))), "\n";

//logout

echo $client->call('endSession', array($session)), "\n";

echo "</pre>";

?>

Tài liệu tham khảo:

http://www.magentocommerce.com/api/soap/introduction.html

CHÚC THÀNH CÔNG!

THÔNG TIN LIÊN HỆ HỖ TRỢ

DVMS

(08) 360 289 37 [email protected]

www.DVMS.vn