magento开发一览

2017-10-23  本文已影响49人  jimxu

author:jim
date: 2016-6-13

文件目录结构

/app –程序根目录
/app/etc –全局配置文件目录
/app/code –所有模块安装其模型和控制器的目录
/app/code/core –核心代码或经过认证得模块,如果要升级不要这里的代码
/app/code/community –社区版的模块目录
/app/code/local –定制代码目录
/app/code/core/Mage –magento默认命名空间
/app/code/core/Mage/{Module} –模块根目录
/app/code/core/Mage/{Module}/etc –模块的配置文件目录
/app/code/core/Mage/{Module}/controllers –模块的控制器
/app/code/core/Mage/{Module}/Block –显示块的逻辑类
/app/code/core/Mage/{Module}/Model –模块的对象模型
/app/code/core/Mage/{Module}/Model/Mysql4 –模块的资源模型
/app/code/core/Mage/{Module}/sql –模块各个版本的安装和升级用sql 
/app/code/core/Mage/{Module}/sql/{resource}/ - 升级是需要的资源模型
/app/code/core/Mage/{Module}/sql/{resource}/{type}-{action}-{versions}.(sql|php) –资源升级文件例如: mysql4-upgrade-0.6.23-0.6.25.sql 
/app/design –设计包目录(layouts, templates, translations) 
/app/design/frontend –前端的设计
/app/design/adminhtml –后台管理设计
/app/design/{area}/{package}/{theme} –定制的主题
/app/design/{area}/{package}/{theme}/layout –定义显示块的 .xml 文件
/app/design/{area}/{package}/{theme}/template – .phtml (html with php tags)模版
/app/design/{area}/{package}/{theme}/locale –Zend_Translate 兼容的主题用的文字翻译
/app/locale –本地化文件
/app/locale/{locale (en_US)} –Zend_Translate 兼容的模块用的文字翻译
/skin/{area}/{package}/{theme}/- css和图像
/lib –公用库
/js – javascripts 
/media –上传文件存放目录
/tests –测试目录
/var –临时文件目录

清除缓存

在终端删除var下的cache文件夹

rm -rf 项目根目录/var/cache    

路由规则

根据类名查找文件路径

用过zend framework的人都知道,自动加载auto loader这个东西,它会跟你类名中的下滑线去你的目录中需要对应的类文件。记住一点,下滑线代表下一级别的文件夹,如果你的类名与你的文件目录名不一 致,那么Magento根本不会理睬你。
举例来说:

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

禁用模块

<active>true</active>
<codePool>community</codePool>

将true置为false并刷新缓存   
* 在app/etc/local.xml中禁用所有的local模块    
        
        <disable_local_modules>false</disable_local_modules> 

##MVC架构
PHP 的 MVC 架构:

在典型的 MVC 模式中,应用程序的流程是这样的:

>1.主入口点:index.php 由整个应用程序的路由机制来决定。

>2.在此基础上的路由机制和请求的URL模式,应用程序将调用相应的控制器。

>3.然后控制器调用相应的视图。

>4.最后,查看文件收集模型文件中的数据和显示数据    
    

Magento 的 MVC架构:

>1.主入口点:index.php 在此整个应用程序将被初始化。

>2.相应的请求的URL在对应的控制器上会被调用。

>3.控制器定义了页面和加载布局文件的那些页面。

>4.布局文件告诉该块文件使用的控制器。

>5.阻止文件收集模型和助手文件中的数据,并把它传递给模板文件。

>6.模板文件接收数据,并渲染HTML。

##程序序列图
![](http://admclub.com/wp-content/uploads/2012/02/Magento的程序序列图.png)
##核心模块
##核心模块关系图
![](http://admclub.com/wp-content/uploads/2012/02/Magento核心模块关系图.png)
##重写block、controller、Model、Helper
参考:[https://www.magentonotes.com/overload_magento_controller.html](https://www.magentonotes.com/overload_magento_controller.html)


##创建数据库

1. 建立模块   
2. 在系统的配置文件中激活模块
3. 在模块的配置文件中
4. 创建模型

    ![](https://segmentfault.com/img/bVtitE)

5. 创建集合类
    ![](https://segmentfault.com/img/bVtPaN)    
       
##获取所有启用的支付模块

class Alwayly_Vendor_Model_Activpayment
{

public function getActivPaymentMethods()
{
   $payments = Mage::getSingleton('payment/config')->getActiveMethods();

   $methods = array(array('value'=>'', 'label'=>Mage::helper('adminhtml')->__('--Please Select--')));

   foreach ($payments as $paymentCode=>$paymentModel) {
        $paymentTitle = Mage::getStoreConfig('payment/'.$paymentCode.'/title');
        $methods[$paymentCode] = array(
            'label'   => $paymentTitle,
            'value' => $paymentCode,
        );
    }

    return $methods;

} 

}

##常用方法
- 获取session

$session = Mage::getSingleton('customer/session');

- Request对象

Mage::app()->getRequest()

- 调用Model对象

Mage::getModel('infinity/model');

- 获取当前时间

Mage::getModel('core/date')->date(); date("Y-m-d", Mage::getModel('core/date')->timestamp(time()));

- session,cookie设置

    - Model:

    Mage::getModel(‘core/cookie’); Mage::getModel(‘core/session’);

    - Set Method:

    Mage::getSingleton(‘core/cookie’)->set(‘name’,'value’); Mage::getSingleton(‘core/session’)->set(‘name’,'value’);

    - Get method:
    
    Mage::getSingleton(‘core/cookie’)->get(‘name’); Mage::getSingleton(‘core/session’)->get(‘name’);

- 输出配置文件

//header(‘Content-Type: text/xml’); header(‘Content-Type: text/plain’); echo $config = Mage::getConfig() ->loadModulesConfiguration(‘system.xml’) ->getNode() ->asXML(); exit;

- Get URL for a Magento Category

Mage::getModel('catalog/category')->load(17)->getUrl();

- build your URL with valid keys

Mage::helper("adminhtml")->getUrl("mymodule/adminhtml_mycontroller/myaction/",array("param1"=>1,"param2"=>2));

- create key values

Mage::getSingleton('adminhtml/url')->getSecretKey("adminhtml_mycontroller","myaction");

- disable security feature in the admin panel

admin panel -> System -> Configuration -> Admin section: “Add Secret key to Urls”.

- 后台模块跳转

Mage::app()->getResponse()->setRedirect(Mage::helper('adminhtml')->getUrl("adminhtml/promo_quote/index"));

- 产品属性操作

$product = Mage::getModel('catalog/product')->getCollection()->getFirstItem(); foreach($product->getAttributes() as $att) { $group_id   = $att->getData('attribute_group_id'); $group      = Mage::getModel('eav/entity_attribute_group')->load($group_id); var_dump($group); } $attrSetName = 'my_custom_attribute'; $attributeSetId = Mage::getModel('eav/entity_attribute_set') ->load($attrSetName, 'attribute_set_name') ->getAttributeSetId();

- get a drop down lists options for a mulit-select attribute

$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'attribute_id'); foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){ $attributeArray[$option['value']] = $option['label']; }

- 获取栏目图片

public function getImageUrl($category) { return Mage::getModel('catalog/category')->load($category->getId())->getImageUrl(); } public function getThumbnailUrl($category) { $image=Mage::getModel('catalog/category')->load($category->getId())->getThumbnail(); if ($image) { $url = Mage::getBaseUrl('media').'catalog/category/'.$image; } return $url; }

- 产品缩略图

$_thumb = Mage::helper('catalog/image')->init($product, 'thumbnail')->resize(50, 50)->setWatermarkSize('30×10');

- 判断是否首页:$this->getIsHomePage()

Mage::getSingleton('cms/page')->getIdentifier() == 'home'  && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms' )


- 获取configurable产品simple product

if($_product->getTypeId() == "configurable"): $ids = $_product->getTypeInstance()->getUsedProductIds(); foreach ($ids as $id) : $simpleproduct = Mage::getModel('catalog/product')->load($id); $simpleproduct->getName()." – ".(int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty(); $childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);

- get the attributes of Configurable Product.

$attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);

- 当前路径

$currentUrl = $this->helper('core/url')->getCurrentUrl();

- 通过资源配置方式创建目录

$installer = $this; $installer->startSetup(); // make directory for font cache try { $domPdfFontCacheDir = join(DS, array('lib', 'Symmetrics', 'dompdf', 'fonts')); $domPdfFontCacheDir = Mage::getBaseDir('var') . DS . $domPdfFontCacheDir; if (!file_exists($domPdfFontCacheDir)) { mkdir($domPdfFontCacheDir, 0777, true); } } catch(Exception $e) { throw new Exception( 'Directory ' . $domPdfFontCacheDir . ' is not writable or couldn\'t be ' . 'created. Please do it manually.' . $e->getMessage() ); } $installer->endSetup();xample"</aParams> <beforeText></beforeText> <afterText></afterText> </action> </reference>

- 在controllers 实现跳转

Mage::app()->getFrontController() ->getResponse() ->setRedirect('http://your-url.com');

- 获取当前站点货币符号

$storeId = (int) $this->getRequest()->getParam('store', 0); $store=Mage::app()->getStore($storeId); $currencyCode=$store->getBaseCurrency()->getCode() $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId); $attributeData = $attribute->getData(); $frontEndLabel = $attributeData['frontend_label']; $attributeOptions = $attribute->getSource()->getAllOptions();

- 获取产品属性集

$sets = Mage::getResourceModel('eav/entity_attribute_set_collection') ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId()) ->load() ->toOptionHash();

- magento使用sql

$resource = Mage::getSingleton('core/resource'); $read= $resource->getConnection('core_read'); $tempTable = $resource->getTableName('infinity_contacts'); $_storeid = Mage::app()->getStore()->getId(); $wheres = "`status`=1 AND ( FIND_IN_SET(0, `store_id`)>0 OR FIND_IN_SET($_storeid, `store_id`)>0 )"; $select = $read->select() ->from($tempTable, array('count(*) as num')) ->where($wheres);

- 设置meta信息

$template = Mage::getConfig()->getNode('global/page/layouts/'.Mage::getStoreConfig("featuredproducts/general/layout").'/template'); $this->loadLayout(); $this->getLayout()->getBlock('root')->setTemplate($template); $this->getLayout()->getBlock('head')->setTitle($this->__(Mage::getStoreConfig("featuredproducts/general/meta_title"))); $this->getLayout()->getBlock('head')->setDescription($this->__(Mage::getStoreConfig("featuredproducts/general/meta_description"))); $this->getLayout()->getBlock('head')->setKeywords($this->__(Mage::getStoreConfig("featuredproducts/general/meta_keywords"))); $this->renderLayout();
上一篇 下一篇

猜你喜欢

热点阅读