Upload
magecom-ukraine
View
2.852
Download
2
Embed Size (px)
Citation preview
Тулика ЕвгенийMagento DeveloperProfessional Services Team
Шаблоны корпоративных приложений в Magento
Craig Larman
Шаблоны. Почему о них говорят?
BШаблоны не содержат новых идей
CШаблоны имеют имена
DШаблоны облегчают общение
Domain Logic
Object-Relational Behavior
Data SourceArchitecture
• Transaction Script• Domain Model
• Data Mapper• Table Data Gateway• Active Record
• Identity Map• Lazy Load
Представление бизнес-логики
Простой путь: декомпозиция по действиям
AccountActions+ Login+ Register+ Logout+ ShowAccount
CheckoutActions+ addToCart+ showCheckout+ submitCheckout
Transaction Script
Каждая операция реализована своим методом
public function addToCart(){ //retrieve user data from session //retrieve product from database //add product information to quote //… //… //save quote data to database }
Объектами представлены реальные сущности
Domain Model
Order
Customer_Address
Category Product
Quote Payment Cart
Customer
Business Logic Layer
Расслоение. А как в Magento?
Sales|--Block|--controllers|--etc|--Helper|--Model| |--Mysql4| |-- Billing| |-- Entity| |-- Payment| |-- Order.php| |-- Quote.php
Data Access Objects
Data Mappers
Domain Models
Service Layer
Mapping Objects to Data Source
Data Mapper
ModelsData
/*Осуществляет передачу данных между объектами и базой данных, сохраняя их независимыми друг от друга и от самого маппера*/
Zend Way
• <?php• class App_Model_UserDataMapper• {• public function save(App_Model_User
$user)• {• $dao = $this->getDao();• $id = $user->getId();• if (!$id) {• $id = $dao->insert($user->toArray());
• } else {• $dao->update($user->toArray(),• array(‘id=?’, $id)); • }• $record = $dao->find($id)->current();• $user->setOptions($record->toArray());• return $user;• }
Matthew Weier O’Phinney
Вернемся к Magento
Sales|--Block|--controllers|--etc|--Helper|--Model| |--Mysql4| | |--Order.php| | |--Quote.php| |-- Billing| |-- Entity| |-- Payment| |-- Order.php| |-- Quote.php
Ресурс-модели
<global> <models> <sales> <class>Mage_Sales_Model</class> <resourceModel>sales_mysql4</resourceModel> </sales> <sales_mysql4> <class>Mage_Sales_Model_Mysql4</class> <sales_mysql4> <sales> <models> <!-- ... --></global>
Mage::getResourceModel('sales/order'); ->load($order, $id, $field);
• public function load(Mage_Core_Model_Abstract $object, $value, $field=null)
• {• if (is_null($field)) {• $field = $this->getIdFieldName();• }
• $read = $this->_getReadAdapter();• if ($read && !is_null($value)) {• $select = $this-
>_getLoadSelect($field, $value, $object);• $data = $read->fetchRow($select);• if ($data) {• $object->setData($data);• }• }• $this->_afterLoad($object);• • return $this;• }
Mage_Core_Model_Mysql4_Abstract
Структура ресурс-модели
Mage_Core_Model_Mysql4_Abstract
+ getMainTable()+ load()+ save()+ delete()#_prepareDataForTable()
Mage_Core_Model_Resource_Abstract
#_getWriteAdapter()#_getReadAdapter()+ beginTrasnsaction()
Отличия от классикиДоменные модели знают о своих ресурс-
моделях
public function getProductIds() { $ids = $this->getData('product_ids'); if (is_null($ids)) { $ids = $this->_getResource()->getProductIds($this); $this->setProductIds($ids); } return $ids; }
Mage_Sales_Model_Order
Lazy and Eager Loading
Загрузка по требованию Самостоятельная
загрузка
• Может загрузить излишне много данных
• Все данные есть под рукой
• Все данные есть под рукой
• Может потребоваться слишком много обращений к базе
Lazy Loading in Magento
public function getAddressesCollection() { if (is_null($this->_addresses)) { $this->_addresses = Mage::getResourceModel('sales/order_address_collection') ->setOrderFilter($this); if ($this->getId()) { foreach ($this->_addresses as $address) { $address->setOrder($this); } } } return $this->_addresses; }
Mage_Sales_Model_Order
Альтернативы. Table Data GatewayName City Telephone Age Insurance
Eugene Kyiv +3804456 21 32453453
Igor New York +45066 23452345Model_DbTable_Person
+find()+findWithName()+update()+insert()+delete()
Model_Person
+getName()+getAddress()+sendEmail()+addFriend()+getFRiendSuggestions()
Альтернативы. Active RecordName City Telephone Age Insurance
Eugene Kyiv +3804456 21 32453453
Igor New York +45066 23452345Model_Person
+getName()+getAddress()+sendEmail()+addFriend()+getFriendSuggestions()
+find()+findWithName()+update()+insert()+delete()
Коллекции. Identity Map
Identity Map
empty
getElement(green)
find()
load()Identity Map
return( )
Magento Collections
Sales|--Model| |--Mysql4| | |-- Collection| | | | -- Abstract.php| | | -- Report| | | | -- Collection.php| | |--Order.php| | |--Quote.php| |-- Billing| |-- Entity| |-- Payment| |-- Order.php| |-- Quote.php
Ресурс-коллекции
$children = $this->getResourceCollection() ->setOrderFilter($orderFilter) ->addPaymentIdFilter($paymentId) ->addParentIdFilter($this->getId());
Mage::getResourceModel('sales/order_collection') ->addFieldToSelect(‘*‘) ->setOrder(‘created_at‘, ‘desc');
Структура коллекции
Varien_Data_Collection_Db
+isLoaded()+load()#_loadCache()#_saveCache()
Mage_Core_Model_Mysql4_Collection_Abstract
+addFiedToSelect()+setModel()+setResourceModel()+save()
Varien_Data_Collection
+getItemsByColumnValue()+addItem()+walk()
Countable
IteratorAggregate
Thank [email protected]