Saturday, November 17, 2012

마젠토 region 과 country 코드

마젠토에는 국가별 코드와 이름이 이미 데이터베이스에 기본적으로 저장되어있고, 미국같은 경우는 state 코드/이름 또한 저장되어있습니다.
간혹 개발자가 커스텀으로 모듈이나 템플릿을 만드는 도중 마젠토 데이터베이스에 저장되어있는 국가(country)나 state(region)을 불러내야 할 경우가 있는 있는데, 아마도 아래 코드가 도움이 되리라 생각됩니다.

[ccln_php]
// 국가의 콜렉션 로딩
$countryCollection = Mage::getModel('directory/country_api')->items();

// 위의 콜렉션을 select dropdown box에 넣어야 할 경우
?>

[/ccln_php]

국가의 콜렉션을 사용하려면 directory/country_api 모델을 사용해야 합니다.
마찬가지로 region 콜렉션을 사용하려면 아래와 같이 directory/region_api 모델을 사용해야 합니다.

[ccln_php]
// region 콜렉션 로딩
// $counotryCode 는 국가 코드
$regionCollection = Mage::getModel('directory/region_api')->items($countryCode);

// 위의 콜렉션을 select dropdown box에 넣어야 할 경우
?>

[/ccln_php]


국가 코드로 국가 이름 불러오기
[ccln_php]
$countryName = Mage::getModel('directory/country')->load($countryCode)->getName();
?>
[/ccln_php]

Tuesday, October 30, 2012

Zend Framework 1 and Zend Framework 2

Zend, a PHP company, released Zend Framework 2 stable version recently and I started working on some projects using Zend Framework 2 right after it came out.
I've been working on Magento(an E-Commerce platform that is built on top of Zend Framework 1) for last 4 years.
At the time I started working on Magento, I knew what Zend Framework was but never had any experience with it.
I had more experience with CodeIgniter and I thought CodeIgniter would be a better platform for its simplicity.
However, after I worked on Magento for several months, I became a big fan of Magento and Zend Framework.
Of course, I've been struggling for first couple weeks because of its complexity - I wasn't familiar with Singleton pattern and EAV model.
Now I have more favor on Zend Framework over CodeIgniter.
I would say Zend Framework is complex and difficult to learn than any other PHP frameworks out there, but I think it's the best framework on the market right now.

Features and concepts overview on ZF1 and ZF2:

Main features on Zend Framework 1:

  • MVC(Model View Controller) architecture

  • Singleton

  • Registries

  • Hard & Soft coded Dependencies

  • Loosely coupled architecture



 

Zend Framework 2 resembles Zend Framework 1 in many ways, but it works differently.

Main features on Zend Framework 2:

  • Event Driven Services - Event Manager & Service Manager

  • Dependency Injection - to avoid dependencies, ZF2 uses events

  • Aspect Oriented Programming - shape the workflow using event manager

  • Namespaces - requires PHP 5.3

  • Lambda functions

  • developers can install only the components desired - don't need to install entire framework



 

Useful resources on ZF2:

Wednesday, October 17, 2012

Richard Dawkins at Macky Auditorium

I was at Macky Auditorium(University of Colorado at Boulder) to see evolutionary biology icon and one of my favorite scientists - Richard Dawkins - Monday night.
Dr. Dawkins was there to have a speech/lecture on very basic natural world questions - but very hard for ordinary people to answer - such as What are things made of? What is reality? Why do bad things happen? Are we alone?, etc.
His explanations are all evidence-based, precise and accurate. His book "The Magic of Reality" is even more descriptive and well explained, even middle school kids can understand.
It was just amazing to see him having a speech in auditorium and also in person at the book signing session.
He looked little older than I imagined, but maybe that's because I only have seen his old photos and movie clips.


Sunday, October 14, 2012

새로운 디자인

새로운 디자인으로 블로그를 바꿨다.
이미지 사이즈가 엄청 큰걸 요구하지만 그래도 사진 갤러리가 제일 맘에든다.
여전히 사진 작업해야 할것들이 조금 남아있고, 다른것들은.. 맘에 들지 않거나 제대로 작동하지 않는것들이 몇가지 있는데.. 그것들은 천천히 하나씩 고치기로 하고..
일단 오늘은 이걸로 끝.

Saturday, August 18, 2012

마젠토에 category attribute 생성 및 삭제

마젠토는 EAV(Entity Attribute Value) 모델을 사용함으로써 각각의 객체모델에 attribute과 attribute의 값어치(value)를 생성시킬수 있습니다.
예를들어 product model 같은경우 마젠토 admin에서 새로운 product attribute을 생성시킬수 있습니다. 그리고 그 attribute의 갯수는 얼마든지 무한대로 늘일수 있습니다.

하지만 category model의 경우 마젠토 admin에서 새로운 category attribute을 생성시키는 기능이 없기 때문에 새로운 attribute을 카테고리에 더하고 싶어도 할수가 없습니다.
사실 마젠토 admin에서 category attribute을 생성시키는 기능이 없는 것일뿐 못하는것은 아닙니다.
마젠토는 EAV 모델을 사용하고 있고 product model과 마찬가지로 category model 또한 entity이며 그 entity에는 attribute과 value를 생성시킬수 있기 때문에 category attribute도 생성시킬수 있습니다.

그렇다고 이것을 phpMyAdmin 이나 adminer 같은 데이터베이스 툴을 사용해서 데이터베이스에 직접 attribute을 생성시키는것은 많은 위험이 따르구요,
아래와 같은 코드로 손쉽게 생성 및 삭제시킬수 있습니다.

category attribute 생성
[ccln_php]
// 마젠토 로딩
Mage::app();

// EAV 모델 셋업 model
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

// 이미지 셀렉터 생성
$setup->addAttribute('catalog_category', 'extra_image', array(
'group' => 'General',
'input' => 'image',
'type' => 'varchar',
'label' => 'Slider Image',
'backend' => 'catalog/category_attribute_backend_image',
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

// 텍스트 필드 생성
$setup->addAttribute('catalog_category', 'extra_text', array(
'group' => 'General',
'input' => 'textarea',
'type' => 'text',
'label' => 'SEO Text',
'backend' => '',
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

// Yes, No같은 boolean value 생성
$setup->addAttribute('catalog_category', 'extra_boolean', array(
'group' => 'General',
'input' => 'select',
'type' => 'int',
'label' => 'Yes or No',
'backend' => '',
'source' => 'eav/entity_attribute_source_boolean',
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
?>
[/ccln_php]

위의 코드는 extra_image, extra_text 그리고 extra_boolean 이란 category attribute을 생성시키는 코드구요, 마젠토 admin에서 category로 들어가시면 각각의 카테고리에 3개의 새로생긴 필드를 찾을수 있습니다.
각각의 attribute에서
group은 attribute이 나오는 그룹
input은 input 필드의 타입
type은 데이터베이스에 저장되는 value의 type
label은 admin에 나오는 텍스트 레이블
backend는 input 필드가 사용할 model
source는 기본적으로 데이터베이스에 저장되어 있는 값어치
를 나타냅니다.

반대로 생성된 attribute을 삭제하는 방법은 아래 코드를 참조하세요.
[ccln_php]
// 마젠토 로딩
Mage::app();

// EAV 모델 셋업 model
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

// category attribute 삭제
$setup->removeAttribute('catalog_category', 'extra_image');
$setup->removeAttribute('catalog_category', 'extra_text');
$setup->removeAttribute('catalog_category', 'extra_boolean');
?>
[/ccln_php]

위의 코드는 새로 생성된 3개의 category attribute을 삭제시킵니다.

Wednesday, March 28, 2012

마젠토 콜렉션(Collection) 사용하기

마젠토 콜렉션(Collection)은 한번에 여러개의 객체(product, customer, category 등등)를 불러오는데 사용됩니다.
예를들어 카테고리 페이지에있는 모든 제품을 불러온다던지, 모든 커스토머(customer) 정보를 불러올때 유용하게 쓰입니다.

아래와 같은 php코드를 루트에 올려놓고 시험해 보세요.
[ccln_php]
require_once "app/Mage.php";
Mage::app();

// 모든 제품 불러오기
$collection = Mage::getResourceModel('catalog/product_collection'); // 첫번째 방법
$collection = Mage::getModel('catalog/product')->getCollection(); // 두번째 방법

// 모든 제품이 필요하지는 않으므로 5개만 로드합니다.
$collection->getSelect()->limit(5);
$collection->load(); // 콜렉션을 불러옵니다.
foreach($collection AS $product) {
// 제품의 모든 데이터 출력
print_r($product->getData());
}
[/ccln_php]
위의 코드를 실행해 보시면 제품의 모든 데이터가 출력이 됩니다.
콜렉션 객체를 불러올때 두가지 방법을 보여드렸는데 첫번째 방법과 두번째 방법의 결과가 약간은 틀린걸 확인할수 있습니다.

첫번째 방법은 최소한의 데이터만 로드함으로써 메모리의 사용을 최대한 줄이는 방법이고,
$collection = Mage::getResourceModel('catalog/product_collection');

두번째 방법은 제품의 모든 데이터를 불러옴으로써 메모리 사용에 상관없이 콜렉션을 사용하는 방법입니다.
$collection = Mage::getModel('catalog/product')->getCollection();

개인적으로 메모리 사용이 적은 첫번째 방법을 선호합니다.
그렇다고 필요한 제품의 데이터를 불러오지 못하는것은 아닙니다.
아래와 같이 addAttributeToSelect()을 사용해서 필요한 Attribute을 불러올수 있습니다.
[ccln_php]
require_once "app/Mage.php";
Mage::app();

$collection = Mage::getResourceModel('catalog/product_collection');

// 아래처럼 원하는 attribute을 콜렉션에 포함시킬수 있습니다.
$collection->addAttributeToSelect('price');
$collection->addAttributeToSelect('weight');

// 모든 제품이 필요하지는 않으므로 5개만 로드합니다.
$collection->getSelect()->limit(5);
$collection->load(); // 콜렉션을 불러옵니다.
foreach($collection AS $product) {
// 제품의 모든 데이터 출력
print_r($product->getData());
}
[/ccln_php]


Attribute으로 불러올 데이터를 addAttributeToFilter()를 사용해서 걸러낼수도 있습니다.
예를들어 id가 10보다 커야 한다던지 sku가 'abcd'를 포함해야 하는경우 아래와 같이 콜렉션을 설정할수 있습니다.
[ccln_php]
require_once "app/Mage.php";
Mage::app();

$collection = Mage::getResourceModel('catalog/product_collection');

// 아래처럼 원하는 attribute을 콜렉션에 포함시킬수 있습니다.
// product entity_id가 10보다 커야하는경우
$collection->addAttributeToFilter('entity_id', array('gt' => 10));

// price가 $100 이하여야 하는 경우
$collection->addAttributeToFilter('price', array('lt' => 100));

// sku가 'abcd'를 포함해야 하는 경우
$collection->addAttributeToFilter('sku', array('like' => '%abcd%'));

// sku가 'zzz1'이 아니어야 하는 경우
$collection->addAttributeToFilter('sku', array('neq' => 'zzz1'));

// description이 아무것도 없는 제품을 포함하는 경우
$collection->addAttributeToFilter('description', 'null');

$collection->load(); // 콜렉션을 불러옵니다.
foreach($collection AS $product) {
// 제품의 모든 데이터 출력
print_r($product->getData());
}
[/ccln_php]

이런식으로 addAttributeToSelect()나 addAttributeToFilter()를 사용해서 원하는 attribute을 콜렉션에 포함시키거나 필터를 적용해서 걸러낼수 있습니다.
콜렉션의 사용은 한번에 많은 객체를 불러와야 할때, 또 한번에 여러 객체의 정보를 수정해야할때 유용하게 쓰입니다.

Tuesday, March 20, 2012

네이버 미국,캐나다 지역 키워드광고 대행

네이버 미국,캐나다 지역 키워드광고 대행



네이버가 미주(미국,캐나다)지역으로 영역을 넓히면서(http://us.naver.com) 광고영업 또한 확장하고 있습니다.
네이버의 주된 광고상품은 크게 디스플레이 광고(배너 광고)와 키워드 광고가 있는데 이번에 제가 네이버 미주지역의 키워드 광고 대행을 맡았습니다.

미주지역에서의 네이버 광고는 크게 디스플레이광고키워드광고로 나뉠수 있는데요,
디스플레이광고는 주로 가격이 비싼 배너광고이고, 키워드광고는 키워드 검색결과내에 보여지는 좀더 저렴한(월$100부터) 광고입니다.
미주지역의 키워드 광고는 한국내 키워드광고 같은 PPC(Pay Per Click)나 CPC(Cost Per Click)이 아닌 CPM(Cost Per Milli)의 성격을 가집니다.
쉽게말해 한국에서의 키워드 광고는 사용자가 클릭하는 숫자 만큼 지불해야하지만, 미주지역의 키워드 광고는 사용자의 클릭수와 관계없이 정해진 금액으로 일정한 광고위치를 구매하는것입니다.
NHN USA Inc. 관계자에 따르면 아직 시작하는 단계이기 때문에 단순한 모델로 시작한다고 하는데요, 결국엔 미주지역의 키워드 광고도 한국의 키워드 광고처럼 PPC/CPC 모델로 바뀐다고 합니다.

미주지역 네이버 키워드 광고에 대한 자세한 내용 및 문의는 아래 링크를 참조해 주시기 바랍니다.
네이버 미주 키워드 광고 문의

Tuesday, March 6, 2012

Magento Certified Developer PLUS

Magento Certified Developer PLUS



Magento Certified Developer Plus

Magento Certified Developer Plus

I just passed the Magento Certified Developer Plus exam.
It's wasn't easy but I would say it wasn't too difficult either.
Probably that's because I've seen a lot of postings and comments on other websites and blogs about Certified Developer PLUS exam being too intense, and to be honest, I didn't feel like I was ready and I thought I would fail the exam even before I take it.

Overall, if you're familiar with the Magento fundamentals, have good enough experience on Magento and confident about custom module/extension development, you don't have to worry about the exam.
If you don't have much experience with Magento, but you studied the Magento Certification Study Guide thoroughly, you might be ok, but at the same time, you could feel that exam questions are tricky and confusing.
Other than that, don't take it until you feel comfortable with Magento.

P.S
I have 3+ years of experience with Magento from version 1.3 to 1.11, and have worked on more than 25+ Magento websites.

For more information about the certification: Magento Developer Certification

Thursday, January 19, 2012

준비하는 자가 승리한다

준비하는 자가 승리한다
불길이 무섭게 타올라도 끄는 방법이 있고
물결이 하늘을 뒤덮어도 막는 방법이 있으니

화는 위험한 때 있는 것이 아니고
편안할 때 있으며

복은 경사 때 있는 것이 아니라
근심할 때 있는 것이다.

- 매월당 김시습 -

Thursday, January 5, 2012

마젠토의 싱글턴 패턴

마젠토의 싱글턴 패턴
getSingleton()과 getModel()의 차이점과 사용법



싱글턴 패턴은 하나의 클래스에서 하나의 인스턴스만을 생성하도록 하는 소프트웨어 디자인 패턴중의 하나입니다.
마젠토에서 이런 싱글턴 패턴의 사용은 객체의 인스턴스 생성 남용을 막으려는 방법이고 결과적으로 메모리의 사용을 최소화하기 위한 방책입니다.

예를 들자면 데이터베이스 인스턴스가 가장 대표적인 예입니다.
페이지가 로딩되면서 여러번의 데이터베이스 사용이 필요할수 있지만 데이터베이스 연결 인스턴스는 하나면 족합니다.
데이터베이스를 사용할때마다 똑같은 데이터베이스에 연결시키는 인스턴스를 여러번 생성하게되면 불필요한 리소스를 낭비하게 됩니다.
이럴때 이미 생성된 데이터베이스 인스턴스를 재활용하고자 하는것이 기본적인 싱글턴 패턴의 컨셉트 입니다.

마젠토에서 객체 인스턴스를 생성하는 방법은 getSingleton('모델/클래스'); 또는 getModel('모델/클래스'); 이 사용되는데 getSingleton('모델/클래스')의 경우 인스턴스가 이미 생성되어있지 않은경우 getModel('모델/클래스') method를 호출하게 됩니다.
아래는 app/Mage.php의 getSingleton() 와 getMethod() method입니다.
[ccln_php]
// getSingleton
public static function getSingleton($modelClass='', array $arguments=array())
{
$registryKey = '_singleton/'.$modelClass;
if (!self::registry($registryKey)) {
self::register($registryKey, self::getModel($modelClass, $arguments));
}
return self::registry($registryKey);
}

// getModel
public static function getModel($modelClass = '', $arguments = array())
{
return self::getConfig()->getModelInstance($modelClass, $arguments);
}
[/ccln_php]

getModel()의 사용예
[ccln_php]
// $productId를 이용한 product 객체의 인스턴스 생성,
$product = Mage::getModel('catalog/product')->load($productId);
// product의 이름 가져오기
$name = $product->getName();
[/ccln_php]

getSingleton()의 사용예
[ccln_php]
// customer session 불러오기
$customerSession = Mage::getSingleton('customer/session');
// customer 인스턴스 불러오기
$customer = $customerSession->getCustomer();
[/ccln_php]

getModel()과 getSingleton()의 비교

[ccln_php]
// getSingleton()을 사용하여 product 객체를 product_id 34로 로딩
$product = Mage::getSingleton('catalog/product')->load(34);
echo $product->getId(); // 34 가 출력됨

// getModel()을 사용하여 product 객체를 로딩
$product = Mage::getModel('catalog/product');
echo $product->getId(); // 아무것도 출력되지 않음
// getModel()은 새로운 객체를 생성하기 때문에 아무것도 출력되지 않음

// getSingleton()을 사용하여 이미 존재하는 product 객체를 로딩
$product = Mage::getSingleton('catalog/product');
echo $product->getId(); // 34 가 출력됨
[/ccln_php]

line 11의 경우, getSingleton()은 이미 생성된 객체를 불러오기 때문에 굳이 product_id 를 로딩하지 않아도 위의 line 2에서 생성된 객체를 자동으로 로딩하게 됩니다.
그래서 line 12에서는 기존에 로딩되어있던 product 객체의 id를 출력하게 됩니다.

Wednesday, January 4, 2012

마젠토의 장점과 단점

마젠토의 장단점 비교
마젠토의 무한한 확장성은 커다란 장점,
단점은 고성능 호스팅 환경 요구



마젠토가 현존하는 최고의 쇼핑몰 플랫폼인것은 알만한 사람들은 이미 다 알고 있습니다.
저도 처음 마젠토를 접했던 2008년에는 긴가민가 했는데 여러 플랫폼을 직접 접해본 결과 확실히 마젠토가 우월함을 느낄수 있었습니다.

다른 쇼핑몰 플랫폼들은 예전부터 널리 사용되어 왔지만 2007년에 나와 2008년부터 유명세를 타기 시작한 마젠토는 osCommerce(오에스커머스)나 Zen Cart(젠카트)같은 기존의 강자들을 제처버리고 우위를 차지하기 시작했습니다.
현재도 계속 진행형입니다.
아래 그래프는 Google Trends에서 가져온 스냅샷입니다.
물론 Google Trends가 절대적 평가는 아니지만 대체적인 흐름은 비슷합니다.

마젠토 vs osCommerce vs Zen Cart

이런 마젠토에 장점이 있는가 하면 단점도 있기에 한번 살펴보겠습니다.

마젠토의 장점:


1. 무한한 확장성을 가진 오픈소스
마젠토는 오픈소스입니다.
게다가 강력한 젠드 프레임워크에 기반해 만들어진 마젠토는 MVC(Model, View, Controller) 패턴을 사용하고 있어 php로 프로그래밍을 할수 있는 개발자라면 얼마든지 모듈이나 익스텐션을 만들수 있습니다.
그리고 코어소스는 물론이고 다수의 익스텐션들 또한 공개되어 있어 쇼핑몰을 수정하고 개편하는데 상당히 수월합니다.

2. 강력한 기능의 쇼핑몰 플랫폼
마젠토는 기본적으로 사용자가 기대하고 있는 많은 기능들이 이미 기본으로 탑재되어 있습니다.
프로모션이나 마케팅 도구는 물론이고 Google Base, Google Analytics, Google Checkout등등 3rd party 서비스들 또한 쉽게 사용할수 있도록 개발되어 있습니다.
물론 페이팔이나 미국에서 많이 사용되고 있는 Authorize.net같은 페이먼트 서비스도 기본적으로 구비되어 있습니다.
작년에 eBay가 마젠토를 사들인것은 더욱더 고무적인 일입니다.

3. 풍부한 관련 자료
한글로된 자료는 아직까지 많이 부족한 편이지만 다른 언어로는 상당히 많은 자료가 존재합니다.
특히 마젠토 홈페이지의 기본정보 Wiki나 Knowledge Base는 물론 커뮤니티가 상당히 커서 다른 플랫폼에 비해 많은 정보가 있습니다.
영어가 가능한 사람들은 질문을 하고 답변을 얻는데 그리 어렵지 않으리라 생각됩니다.
그리고 수많은 템플렛과 익스텐션, 모듈등이 이미 개발되어 있어서 새로운 기능을 추가하는데 큰 불편함이 없습니다.


마젠토의 단점:


1. 초보자가 사용하기에 복잡한 구조
장점으로 꼽히는 젠드 프레임워크 기반의 MVC 패턴은 실력있는 개발자에겐 어마어마한 장점으로 다가올수 있지만, 반대로 초보자에게는 새로운 기능을 추가하거나 기존의 기능을 수정하는데 어려움을 줄수 있습니다.
기본적으로 탑재되어 있는 기능들도 많기 때문에 익숙해지는데 시간이 조금 걸립니다.

2. 고성능 서버 환경 요구
마젠토의 단점중 하나가 느린 스피드(많은 하드웨어 리소스를 요구) 입니다.
물론 고급 서버에 호스팅을 하고 있으면 자연히 해결될수 있는 부분이지만 소규모 온라인 쇼핑몰을 운영하는 사람들에겐 부담이 될수 있습니다.
기업수준의 쇼핑몰을 운영하는 사람은 부담없이 마젠토를 선택할수 있어도 매출이 적은 쇼핑몰 운영자는 값비싼 호스팅을 유지하거나 저렴한 호스팅에서 느린 사이트를 운영하는 수 밖에 없습니다.

3. 아직까지는 값비싼 개발자/개발업체
저도 미국에서 마젠토 개발자로 일하고 있지만 현재 일하고 있는 회사에서도 마젠토 개발자를 구하는게 쉽지 않습니다.
경험있는 개발자를 구하는게 쉽지않고 실력있는 마젠토 개발자는 더더욱 구하기 어렵습니다.
이것은 마젠토 사이트를 구축하는데 드는 비용이 싸지 않다는것을 반증합니다.
마젠토 홈페이지에는 파트너 리스트(Gold, Silver, Bronze)가 있기 때문에 마젠토 개발업체를 골라서 견적을 낼수 있습니다.

 

직업상 마젠토를 이용해 수십개의 사이트를 개발해왔고 다른 플랫폼에서 마젠토로 옮겨온 수많은 클라이언트들의 경험담을 들어보면 옮긴걸 후회하는 사람들은 단 한명도 없었습니다.
대다수가 상당히 만족하고 있으며 이미 잘 짜여진 시스템이 검색엔진 최적화에도 상당히 좋은 결과를 가져다주기 때문에 매출이 훨씬 올라간 클라이언트들이 많습니다.
저렴한 호스팅에서 조금 느리다는것을 불평하는 클라이언트들은 있었지만 그 기능과 무한한 확장성은 어느 유수의 쇼핑몰 플랫폼보다 낫다고 확신합니다.

Monday, January 2, 2012

마젠토 객체의 데이터 불러오기

마젠토 getModel()과 getData()를 사용한 객체의 데이터 불러오는 방법



마젠토 객체의 데이터를 불러오는 방법입니다. getModel()과 getData()를 사용하며 마젠토의 객체를 불러오는 방식은 대부분 동일합니다.

마젠토에서는 객체를 불러올때 대체로 getModel() method를 사용하고 불러온 객체의 데이터를 가져올때 getData() method를 사용합니다.
method의 이름이 무엇을 할때 쓰이는지 이미 알려주듯이 사용법 또한 그리 어렵지 않습니다.
이번 포스팅에서는 객체를 불러와 객체를 아이디로 로드하는 방법, 그리고 객체내에 있는 데이터를 불러오는 방법을 보여드립니다.

예를들어 product 객체를 불러올때엔 아래와 같은 코드를 실행하시면 됩니다.
[ccln_php]
$product = Mage::getModel('catalog/product');
?>
[/ccln_php]
한마디로 Mage_Catalog_Model_Product의 객체를 불러오는 것이며 getModel() 안에있는 'catalog/product'는 Mage_Catalog_Model_Product 를 나타냅니다.
Mage_Catalog_Model_Product는 /app/code/core/Mage/Catalog/Model/Product.php 에 위치하고 있으며 Mage_Catalog_Model_Abstract 에서 계승되어 내려온 클래스입니다.
다른 객체를 불러올때도 같은 방법을 사용하며 파일의 위치또한 같은 형식의 폴더안에 위치해 있습니다.

category 객체나 customer 객체를 불러올때도 같은 형식입니다.
[ccln_php]
$category = Mage::getModel('catalog/category');
$customer = Mage::getModel('customer/customer');
?>
[/ccln_php]
category의 경우 Mage_Catalog_Model_Category의 객체를 불러오는 것이며 해당 파일은 /app/code/core/Mage/Catalog/Model/Category.php 에 위치해 있습니다.
customer의 경우 Mage_Customer_Model_Customer의 객체를 불러오는 것이며 해당 파일은 /app/code/core/Mage/Customer/Model/Customer.php 에 위치해 있습니다.

위와같이 product, category, customer 객체를 불러왔을때엔 그 객체 안에는 아직 아무것도 없고 객체를 사용해서 할수있는 일도 몇가지 안됩니다.
객체를 불러온 후에는 product_id, category_id 또는 customer_id를 사용해서 각각의 정보를 로딩해야 합니다.

아래는 product_id '3'을 가진 product를 $product에 로딩시킨후 로딩된 객체의 정보를 getData() method를 사용해서 프린트하는 코드입니다.
마젠토의 root 폴더에 임의의 파일을 만들어 아래 코드를 복사해서 실행시킬수 있습니다.
[ccln_php]
require_once "app/Mage.php";

$product = Mage::getModel('catalog/product')->load(3);
echo '
'; // 어레이를 조금 보기 쉽게 하기 위해서...
print_r($product->getData());

// product의 이름 출력하는 방법
echo $product->getName();
echo $product->getData('name');
// product의 sku 출력하는 방법
echo $product->getSku();
echo $product->getData('sku');
// product의 가격 출력하는 방법
echo $product->getPrice();
echo $product->getData('price');
?>
[/ccln_php]

print_r($product->getData()); 를 프린트 해 보시면 array 안에 product에 관련된 모든 attribute들이 데이터 형식으로 들어있는것을 볼수 있습니다.
그 데이터를 불러올때엔
$product->get{attribute 이름}(); 형식을 사용하면 되고,
$product->getData('{attribute 이름}');의 형식도 사용 가능합니다.
다만 $product->get{attribute 이름}(); 의 경우 {attribute 이름}의 첫번째 알파벳은 대문자가 되어야 합니다.