Monthly Archives: 十二月 2015

Magento 模拟站点环境

// Start store emulation process
$appEmulation = Mage::getSingleton (‘core/app_emulation’);
$initialEnvironmentInfo = $appEmulation ->startEnvironmentEmulation(Mage_Core_Model_App::ADMIN_STORE_ID);
try
{
   
// Retrieve specified view block from appropriate design package (depends on emulated store)
   
$_product
       
-> unsTierPrice()
        ->
save ()
        ->
setTierPrice ($this-> TierPriceScale($_productPrice ))
        ->
save ();
} catch (Exception $exception) {
   
// Stop store emulation process
   
$appEmulation ->stopEnvironmentEmulation($initialEnvironmentInfo );
    throw
$exception;
}
// Stop store emulation process
$appEmulation ->stopEnvironmentEmulation($initialEnvironmentInfo );

解决Magento1.7 原生优惠券BUG

app\code\core\Mage\Rule\Model\Condition\Abstract.php

<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category    Mage
* @package     Mage_Rule
* @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*/

/**
* Abstract Rule condition data model
*
* @category Mage
* @package Mage_Rule
* @author Magento Core Team <core@magentocommerce.com>
*/
abstract class Mage_Rule_Model_Condition_Abstract
    extends Varien_Object
    implements Mage_Rule_Model_Condition_Interface
{
    /**
     * Defines which operators will be available for this condition
     *
     * @var string
     */
    protected $_inputType = null;
    /**
     * Default values for possible operator options
     * @var array
     */
    protected $_defaultOperatorOptions = null;
    /**
     * Default combinations of operator options, depending on input type
     * @var array
     */
    protected $_defaultOperatorInputByType = null;
    /**
     * List of input types for values which should be array
     * @var array
     */
    protected $_arrayInputTypes = array();
    public function __construct()
    {
        parent::__construct();
        $this->loadAttributeOptions()->loadOperatorOptions()->loadValueOptions();
        if ($options = $this->getAttributeOptions()) {
            foreach ($options as $attr=>$dummy) { $this->setAttribute($attr); break; }
        }
        if ($options = $this->getOperatorOptions()) {
            foreach ($options as $operator=>$dummy) { $this->setOperator($operator); break; }
        }
    }
    /**
     * Default operator input by type map getter
     *
     * @return array
     */
    public function getDefaultOperatorInputByType()
    {
        if (null === $this->_defaultOperatorInputByType) {
            $this->_defaultOperatorInputByType = array(
                ‘string’      => array(‘==’, ‘!=’, ‘>=’, ‘>’, ‘<=’, ‘<‘, ‘{}’, ‘!{}’, ‘()’, ‘!()’),
                ‘numeric’     => array(‘==’, ‘!=’, ‘>=’, ‘>’, ‘<=’, ‘<‘, ‘()’, ‘!()’),
                ‘date’        => array(‘==’, ‘>=’, ‘<=’),
                ‘select’      => array(‘==’, ‘!=’),
                ‘boolean’     => array(‘==’, ‘!=’),
                ‘multiselect’ => array(‘{}’, ‘!{}’, ‘()’, ‘!()’),
                ‘grid’        => array(‘()’, ‘!()’),
            );
            $this->_arrayInputTypes = array(‘multiselect’, ‘grid’);
        }
        return $this->_defaultOperatorInputByType;
    }
    /**
     * Default operator options getter
     * Provides all possible operator options
     *
     * @return array
     */
    public function getDefaultOperatorOptions()
    {
        if (null === $this->_defaultOperatorOptions) {
            $this->_defaultOperatorOptions = array(
                ‘==’  => Mage::helper(‘rule’)->__(‘is’),
                ‘!=’  => Mage::helper(‘rule’)->__(‘is not’),
                ‘>=’  => Mage::helper(‘rule’)->__(‘equals or greater than’),
                ‘<=’  => Mage::helper(‘rule’)->__(‘equals or less than’),
                ‘>’   => Mage::helper(‘rule’)->__(‘greater than’),
                ‘<‘   => Mage::helper(‘rule’)->__(‘less than’),
                ‘{}’  => Mage::helper(‘rule’)->__(‘contains’),
                ‘!{}’ => Mage::helper(‘rule’)->__(‘does not contain’),
                ‘()’  => Mage::helper(‘rule’)->__(‘is one of’),
                ‘!()’ => Mage::helper(‘rule’)->__(‘is not one of’)
            );
        }
        return $this->_defaultOperatorOptions;
    }
    public function getForm()
    {
        return $this->getRule()->getForm();
    }
    public function asArray(array $arrAttributes = array())
    {
        $out = array(
            ‘type’=>$this->getType(),
            ‘attribute’=>$this->getAttribute(),
            ‘operator’=>$this->getOperator(),
            ‘value’=>$this->getValue(),
            ‘is_value_processed’=>$this->getIsValueParsed(),
        );
        return $out;
    }
    public function asXml()
    {
        $xml = “<type>”.$this->getType().”</type>”
            .”<attribute>”.$this->getAttribute().”</attribute>”
            .”<operator>”.$this->getOperator().”</operator>”
            .”<value>”.$this->getValue().”</value>”;
        return $xml;
    }
    public function loadArray($arr)
    {
        $this->setType($arr[‘type’]);
        $this->setAttribute(isset($arr[‘attribute’]) ? $arr[‘attribute’] : false);
        $this->setOperator(isset($arr[‘operator’]) ? $arr[‘operator’] : false);
        $this->setValue(isset($arr[‘value’]) ? $arr[‘value’] : false);
        $this->setIsValueParsed(isset($arr[‘is_value_parsed’]) ? $arr[‘is_value_parsed’] : false);
//        $this->loadAttributeOptions();
//        $this->loadOperatorOptions();
//        $this->loadValueOptions();
        return $this;
    }
    public function loadXml($xml)
    {
        if (is_string($xml)) {
            $xml = simplexml_load_string($xml);
        }
        $arr = (array)$xml;
        $this->loadArray($arr);
        return $this;
    }
    public function loadAttributeOptions()
    {
        return $this;
    }
    public function getAttributeOptions()
    {
        return array();
    }
    public function getAttributeSelectOptions()
    {
        $opt = array();
        foreach ($this->getAttributeOption() as $k=>$v) {
            $opt[] = array(‘value’=>$k, ‘label’=>$v);
        }
        return $opt;
    }
    public function getAttributeName()
    {
        return $this->getAttributeOption($this->getAttribute());
    }
    public function loadOperatorOptions()
    {
        $this->setOperatorOption($this->getDefaultOperatorOptions());
        $this->setOperatorByInputType($this->getDefaultOperatorInputByType());
        return $this;
    }
    /**
     * This value will define which operators will be available for this condition.
     *
     * Possible values are: string, numeric, date, select, multiselect, grid, boolean
     *
     * @return string
     */
    public function getInputType()
    {
        if (null === $this->_inputType) {
            return ‘string’;
        }
        return $this->_inputType;
    }
    public function getOperatorSelectOptions()
    {
        $type = $this->getInputType();
        $opt = array();
        $operatorByType = $this->getOperatorByInputType();
        foreach ($this->getOperatorOption() as $k => $v) {
            if (!$operatorByType || in_array($k, $operatorByType[$type])) {
                $opt[] = array(‘value’ => $k, ‘label’ => $v);
            }
        }
        return $opt;
    }
    public function getOperatorName()
    {
        return $this->getOperatorOption($this->getOperator());
    }
    public function loadValueOptions()
    {
//        $this->setValueOption(array(
//            true  => Mage::helper(‘rule’)->__(‘TRUE’),
//            false => Mage::helper(‘rule’)->__(‘FALSE’),
//        ));
        $this->setValueOption(array());
        return $this;
    }
    public function getValueSelectOptions()
    {
        $valueOption = $opt = array();
        if ($this->hasValueOption()) {
            $valueOption = (array) $this->getValueOption();
        }
        foreach ($valueOption as $k => $v) {
            $opt[] = array(‘value’ => $k, ‘label’ => $v);
        }
        return $opt;
    }
    /**
     * Retrieve parsed value
     *
     * @return array|string|int|float
     */
    public function getValueParsed()
    {
        if (!$this->hasValueParsed()) {
            $value = $this->getData(‘value’);
            if ($this->isArrayOperatorType() && is_string($value)) {
                $value = preg_split(‘#\s*[,;]\s*#’, $value, null, PREG_SPLIT_NO_EMPTY);
            }
            $this->setValueParsed($value);
        }
        return $this->getData(‘value_parsed’);
    }
    /**
     * Check if value should be array
     *
     * Depends on operator input type
     *
     * @return bool
     */
    public function isArrayOperatorType()
    {
        $op = $this->getOperator();
        return $op === ‘()’ || $op === ‘!()’ || in_array($this->getInputType(), $this->_arrayInputTypes);
    }
    public function getValue()
    {
        if ($this->getInputType()==’date’ && !$this->getIsValueParsed()) {
            // date format intentionally hard-coded
            $this->setValue(
                Mage::app()->getLocale()->date($this->getData(‘value’),
                Varien_Date::DATE_INTERNAL_FORMAT, null, false)->toString(Varien_Date::DATE_INTERNAL_FORMAT)
            );
            $this->setIsValueParsed(true);
        }
        return $this->getData(‘value’);
    }
    public function getValueName()
    {
        $value = $this->getValue();
        if (is_null($value) || ” === $value) {
            return ‘…’;
        }
        $options = $this->getValueSelectOptions();
        $valueArr = array();
        if (!empty($options)) {
            foreach ($options as $o) {
                if (is_array($value)) {
                    if (in_array($o[‘value’], $value)) {
                        $valueArr[] = $o[‘label’];
                    }
                } else {
                    if (is_array($o[‘value’])) {
                        foreach ($o[‘value’] as $v) {
                            if ($v[‘value’]==$value) {
                                return $v[‘label’];
                            }
                        }
                    }
                    if ($o[‘value’] == $value) {
                        return $o[‘label’];
                    }
                }
            }
        }
        if (!empty($valueArr)) {
            $value = implode(‘, ‘, $valueArr);
        }
        return $value;
    }
    /**
     * Get inherited conditions selectors
     *
     * @return array
     */
    public function getNewChildSelectOptions()
    {
        return array(
            array(‘value’=>”, ‘label’=>Mage::helper(‘rule’)->__(‘Please choose a condition to add…’)),
        );
    }
    public function getNewChildName()
    {
        return $this->getAddLinkHtml();
    }
    public function asHtml()
    {
        $html = $this->getTypeElementHtml()
           .$this->getAttributeElementHtml()
           .$this->getOperatorElementHtml()
           .$this->getValueElementHtml()
           .$this->getRemoveLinkHtml()
           .$this->getChooserContainerHtml();
        return $html;
    }
    public function asHtmlRecursive()
    {
        $html = $this->asHtml();
        return $html;
    }
    public function getTypeElement()
    {
        return $this->getForm()->addField($this->getPrefix() . ‘__’ . $this->getId() . ‘__type’, ‘hidden’, array(
            ‘name’    => ‘rule[‘ . $this->getPrefix() . ‘][‘ . $this->getId() . ‘][type]’,
            ‘value’   => $this->getType(),
            ‘no_span’ => true,
            ‘class’   => ‘hidden’,
        ));
    }
    public function getTypeElementHtml()
    {
        return $this->getTypeElement()->getHtml();
    }
    public function getAttributeElement()
    {
        if (is_null($this->getAttribute())) {
            foreach ($this->getAttributeOption() as $k => $v) {
                $this->setAttribute($k);
                break;
            }
        }
        return $this->getForm()->addField($this->getPrefix().’__’.$this->getId().’__attribute’, ‘select’, array(
            ‘name’=>’rule[‘.$this->getPrefix().’][‘.$this->getId().’][attribute]’,
            ‘values’=>$this->getAttributeSelectOptions(),
            ‘value’=>$this->getAttribute(),
            ‘value_name’=>$this->getAttributeName(),
        ))->setRenderer(Mage::getBlockSingleton(‘rule/editable’));
    }
    public function getAttributeElementHtml()
    {
        return $this->getAttributeElement()->getHtml();
    }
    /**
     * Retrieve Condition Operator element Instance
     * If the operator value is empty – define first available operator value as default
     *
     * @return Varien_Data_Form_Element_Select
     */
    public function getOperatorElement()
    {
        $options = $this->getOperatorSelectOptions();
        if (is_null($this->getOperator())) {
            foreach ($options as $option) {
                $this->setOperator($option[‘value’]);
                break;
            }
        }
        $elementId   = sprintf(‘%s__%s__operator’, $this->getPrefix(), $this->getId());
        $elementName = sprintf(‘rule[%s][%s][operator]’, $this->getPrefix(), $this->getId());
        $element     = $this->getForm()->addField($elementId, ‘select’, array(
            ‘name’          => $elementName,
            ‘values’        => $options,
            ‘value’         => $this->getOperator(),
            ‘value_name’    => $this->getOperatorName(),
        ));
        $element->setRenderer(Mage::getBlockSingleton(‘rule/editable’));
        return $element;
    }
    public function getOperatorElementHtml()
    {
        return $this->getOperatorElement()->getHtml();
    }
    /**
     * Value element type will define renderer for condition value element
     *
     * @see Varien_Data_Form_Element
     * @return string
     */
    public function getValueElementType()
    {
        return ‘text’;
    }
    public function getValueElementRenderer()
    {
        if (strpos($this->getValueElementType(), ‘/’)!==false) {
            return Mage::getBlockSingleton($this->getValueElementType());
        }
        return Mage::getBlockSingleton(‘rule/editable’);
    }
    public function getValueElement()
    {
        $elementParams = array(
            ‘name’               => ‘rule[‘.$this->getPrefix().’][‘.$this->getId().’][value]’,
            ‘value’              => $this->getValue(),
            ‘values’             => $this->getValueSelectOptions(),
            ‘value_name’         => $this->getValueName(),
            ‘after_element_html’ => $this->getValueAfterElementHtml(),
            ‘explicit_apply’     => $this->getExplicitApply(),
        );
        if ($this->getInputType()==’date’) {
            // date format intentionally hard-coded
            $elementParams[‘input_format’] = Varien_Date::DATE_INTERNAL_FORMAT;
            $elementParams[‘format’]       = Varien_Date::DATE_INTERNAL_FORMAT;
        }
        return $this->getForm()->addField($this->getPrefix().’__’.$this->getId().’__value’,
            $this->getValueElementType(),
            $elementParams
        )->setRenderer($this->getValueElementRenderer());
    }
    public function getValueElementHtml()
    {
        return $this->getValueElement()->getHtml();
    }
    public function getAddLinkHtml()
    {
        $src = Mage::getDesign()->getSkinUrl(‘images/rule_component_add.gif’);
        $html = ‘<img src=”‘ . $src . ‘” class=”rule-param-add v-middle” alt=”” title=”‘ . Mage::helper(‘rule’)->__(‘Add’) . ‘”/>’;
        return $html;
    }
    public function getRemoveLinkHtml()
    {
        $src = Mage::getDesign()->getSkinUrl(‘images/rule_component_remove.gif’);
        $html = ‘ <span class=”rule-param”><a href=”javascript:void(0)” class=”rule-param-remove” title=”‘ . Mage::helper(‘rule’)->__(‘Remove’) . ‘”><img src=”‘ . $src . ‘”  alt=”” class=”v-middle” /></a></span>’;
        return $html;
    }
    public function getChooserContainerHtml()
    {
        $url = $this->getValueElementChooserUrl();
        $html = ”;
        if ($url) {
            $html = ‘<div class=”rule-chooser” url=”‘ . $url . ‘”></div>’;
        }
        return $html;
    }
    public function asString($format = ”)
    {
        $str = $this->getAttributeName() . ‘ ‘ . $this->getOperatorName() . ‘ ‘ . $this->getValueName();
        return $str;
    }
    public function asStringRecursive($level=0)
    {
        $str = str_pad(”, $level * 3, ‘ ‘, STR_PAD_LEFT) . $this->asString();
        return $str;
    }
    /**
     * Validate product attrbute value for condition
     *
     * @param   mixed $validatedValue product attribute value
     * @return  bool
     */
    public function validateAttribute($validatedValue)
    {
        if (is_object($validatedValue)) {
            return false;
        }
        /**
         * Condition attribute value
         */
        $value = $this->getValueParsed();
        /**
         * Comparison operator
         */
        $op = $this->getOperatorForValidate();
        // if operator requires array and it is not, or on opposite, return false
        if ($this->isArrayOperatorType() xor is_array($value)) {
            return false;
        }
        $result = false;
        switch ($op) {
            case ‘==’: case ‘!=’:
                if (is_array($value)) {
                    if (is_array($validatedValue)) {
                        $result = array_intersect($value, $validatedValue);
                        $result = !empty($result);
                    } else {
                        return false;
                    }
                } else {
                    if (is_array($validatedValue)) {
                        $result = count($validatedValue) == 1 && array_shift($validatedValue) == $value;
                    } else {
                        $result = $this->_compareValues($validatedValue, $value);
                    }
                }
                break;
            case ‘<=’: case ‘>’:
                if (!is_scalar($validatedValue)) {
                    return false;
                } else {
                         //解决优惠券BUG
                         if(gettype($validatedValue)!=’integer’&&$this->getAttribute()==’special_to_date’){
                              $validatedValue=strtotime($validatedValue);
                              $value=time();
                         }
                        
                    $result = $validatedValue <= $value;
                }
                break;
            case ‘>=’: case ‘<‘:
                if (!is_scalar($validatedValue)) {
                    return false;
                } else {
                    $result = $validatedValue >= $value;
                }
                break;
            case ‘{}’: case ‘!{}’:
                if (is_scalar($validatedValue) && is_array($value)) {
                    foreach ($value as $item) {
                        if (stripos($validatedValue,$item)!==false) {
                            $result = true;
                            break;
                        }
                    }
                } elseif (is_array($value)) {
                    if (is_array($validatedValue)) {
                        $result = array_intersect($value, $validatedValue);
                        $result = !empty($result);
                    } else {
                        return false;
                    }
                } else {
                    if (is_array($validatedValue)) {
                        $result = in_array($value, $validatedValue);
                    } else {
                        $result = $this->_compareValues($value, $validatedValue, false);
                    }
                }
                break;
            case ‘()’: case ‘!()’:
                if (is_array($validatedValue)) {
                    $result = count(array_intersect($validatedValue, (array)$value))>0;
                } else {
                    $value = (array)$value;
                    foreach ($value as $item) {
                        if ($this->_compareValues($validatedValue, $item)) {
                            $result = true;
                            break;
                        }
                    }
                }
                break;
        }
        if (‘!=’ == $op || ‘>’ == $op || ‘<‘ == $op || ‘!{}’ == $op || ‘!()’ == $op) {
            $result = !$result;
        }
        return $result;
    }
    /**
     * Case and type insensitive comparison of values
     *
     * @param  string|int|float $validatedValue
     * @param  string|int|float $value
     * @return bool
     */
    protected function _compareValues($validatedValue, $value, $strict = true)
    {
        if ($strict && is_numeric($validatedValue) && is_numeric($value)) {
            return $validatedValue == $value;
        } else {
            $validatePattern = preg_quote($validatedValue, ‘~’);
            if ($strict) {
                $validatePattern = ‘^’ . $validatePattern . ‘$’;
            }
            return (bool)preg_match(‘~’ . $validatePattern . ‘~iu’, $value);
        }
    }
    public function validate(Varien_Object $object)
    {
        return $this->validateAttribute($object->getData($this->getAttribute()));
    }
    /**
     * Retrieve operator for php validation
     *
     * @return string
     */
    public function getOperatorForValidate()
    {
        return $this->getOperator();
    }
}

Magento 高级模型EAV

1.EAV模型 定义


<? xml version =“1.0”?>
<config>
    <!–模块声明 –>  
    <modules>
        <Zhlmmc_Helloworld>     <!– 模块的名称 –>
            <version>0.1.0</version>
        </Zhlmmc_Helloworld>
    </modules>

    
    <frontend>
        <routers>
            <helloworld>  
                <use>standard</use>
                <args>
                    <module>Zhlmmc_Helloworld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers> 
    </frontend>
    
    <global>

         <!–普通模型声明–>
         <models>
<group_classname>
          <class>Namespace_Modulename_Model</class>
<group_classname>

             <helloworld> <!– 定义组名, <helloworld />就是组名,也应该和模块名一致。 –>
                 <class>Zhlmmc_Helloworld_Model</class>
                 <!– <class />标签的内容是基本类名,所有 Helloworld模块的模型都用这个基本类名 ,命名方式如下Packagename_Modulename_Model –>
                 <!–  need to create our own resource, can’t justuse core_mysql4–>
                 <!– 模型中的资源模型配对        –>
                 <resourceModel>helloworld_mysql4</resourceModel> <!– <resourceModel />标签指明了这个模块的模型要用哪个资源模型。这个标签的内容是组名加上“ mysql4 –>
             </helloworld>
             <helloworld_mysql4> <!– 资源模型声明 –>   
                 <class>Zhlmmc_Helloworld_Model_Resource_Mysql4</class>
                     <!–资源模型的声明!有点搞,但是也不必深究了, Magento就这么定义的。<class />标签的值是所有资源模型类的基本类名,命名方式如下 Packagename_Modulename_Model_Resource_Mysql4 –>
                  <entities>
                       <blogpost> <!– blogpost”作为实体名,也就是 <blogpost> –>  
                           <table>blog_posts</table>
                       </blogpost>
                   </entities>
             </helloworld_mysql4>    
         </models>
            
         <!– 资源读写适配器声明 –>
         <resources>
             <helloworld_write>
                 <connection>
                     <use>default_write</use>
                 </connection>
             </helloworld_write>
             <helloworld_read>
                 <connection>
                     <use>default_read</use>
                 </connection>
             </helloworld_read>
        
         <!–资源配置–>  
             <helloworld_setup>   <!– modelname_setup”来命名资源配置 –>
                 <setup>
                     <module>Zhlmmc_Helloworld</module>   <!–<module>标签的内容是“ Packagename_Modulename–>
                     <class>Zhlmmc_Helloworld_Model_Setup_Mysql4_Setup</class> <!–<class>标签的内容就是我们将要创建的资源配置类的类名 –>
                 </setup>
                 <connection>
                     <use>core_setup</use>
                 </connection>
             </helloworld_setup>
         </resources>
        


    <!–Eav模型定义 –>
         <models>
             <helloworld-eav><!–定义组名, <helloworld />就是组名,也应该和模块名一致。 –>
                 <class>Zhlmmc_Helloworld_Model</class>
                 <!– <class />标签的内容是基本类名,所有 Helloworld模块的模型都用这个基本类名 ,命名方式如下Packagename_Modulename_Model –>
                 <!–  need to create our own resource, can’t justuse core_mysql4–>
                             <!–
                                Path app\code\local\Zhlmmc\Helloworld\Model\Eavblogpost.php
                                
                                 class Zhlmmc_Helloworld_Model_Eavblogpost extends Mage_Core_Model_Abstract
                                 {
                                     protected function _construct()
                                     {
                                         $this->_init(‘helloworld-eav/blogpost’);
                                     } 
                                 }
                             –>
                 <!– 模型中的资源模型配对        –>
                 <resourceModel>helloworld-eav_mysql4</resourceModel> <!– <resourceModel /> 标签指明了这个模块的模型要用哪个资源模型。这个标签的内容是组名加上“ mysql4 –>
             </helloworld-eav>
             <helloworld-eav_mysql4><!– 定义 Eav模型资源模型 –>
                 <class>Zhlmmc_Helloworld_Model_Resource_Eav_Mysql4</class>
                 <!–资源模型的声明!有点搞,但是也不必深究了, Magento就这么定义的。<class />标签的值是所有资源模型类的基本类名,命名方式如下 Packagename_Modulename_Model_Resource_Mysql4 –>         
                                 <!–
                                Path app\code\local\Zhlmmc\Helloworld\Model\Resource\Eav\Mysql4\Blogpost.php
                                    class Zhlmmc_Helloworld_Model_Resource_Eav_Mysql4_Blogpost extends Mage_Eav_Model_Entity_Abstract
                                     { 
                                         public function _construct()
                                         {
                                             $resource = Mage::getSingleton(‘core/resource’);
                                             $this->setType(‘helloworld_eavblogpost’);
                                             $this->setConnection(
                                                 $resource->getConnection(‘helloworld-eav_read’),
                                                 $resource->getConnection(‘helloworld-eav_write’)
                                                  );
                                         }
                                     }
                                –>  
                 <entities>
                     <blogpost> <!– blogpost”作为实体名,也就是 <blogpost> –>
                         <table>eavblog_posts</table>   
                     </blogpost>
                 </entities>
             </helloworld-eav_mysql4>
         </models>
        
         <!– 注意models resources是独立分开 –>
        
         <!– 定义Eav 模型适配器 –>  
         <resources>
             <helloworld-eav_write>
                 <connection>
                     <use>default_write</use>
                 </connection>
             </helloworld-eav_write>
             <helloworld-eav_read>
                 <connection>
                     <use>default_read</use>
                 </connection>
             </helloworld-eav_read> 
            
             <helloworld-eav_setup><!– modelname_setup”来命名资源配置–>
                 <setup>
                     <module>Zhlmmc_Helloworld</module> <!–<module>标签的内容是“ Packagename_Modulename–>
                     <class>Zhlmmc_Helloworld_Model_Setup_Entity_Setup</class><!–<class> 标签的内容就是我们将要创建的资源配置类的类名 –>
                                 <!–    
                                    Path app\code\local\Zhlmmc\Helloworld\Model\Setup\Entity\Setup.php
                                    class Zhlmmc_Helloworld_Model_Setup_Entity_Setup extends Mage_Eav_Model_Entity_Setup {
                                        public function getDefaultEntities()
                                        {         
                                         return array (
                                             ‘helloworld_eavblogpost’ => array(
                                                 ‘entity_model’      => ‘helloworld-eav/eavblogpost’,
                                                 ‘attribute_model’   => ”,
                                                 ‘table’             => ‘helloworld-eav/blogpost’,
                                                 ‘attributes’        => array(
                                                     ‘title’ => array(
                                                         //the EAV attribute type, NOT a mysql varchar
                                                         ‘type’              => ‘varchar’,
                                                         ‘backend’           => ”,
                                                         ‘frontend’          => ”,
                                                         ‘label’             => ‘Title’,
                                                         ‘input’             => ‘text’,
                                                         ‘class’             => ”,
                                                         ‘source’            => ”,
                                                         // store scope == 0
                                                         // global scope == 1
                                                         // website scope == 2
                                                         ‘global’            => 0,
                                                         ‘visible’           => true,
                                                         ‘required’          => true,
                                                         ‘user_defined’      => true,
                                                         ‘default’           => ”,
                                                         ‘searchable’        => false,
                                                         ‘filterable’        => false,
                                                         ‘comparable’        => false,
                                                         ‘visible_on_front’  => false,
                                                         ‘unique’            => false,
                                                     ),
                                                 ),
                                             )
                                         );
                                        }

                                        }
                                    –>  
                 </setup>
                 <connection>
                     <use>core_setup</use>
                 </connection>
             </helloworld-eav_setup>
         </resources>
        
    </global>

</config> 
    
    


2.控制器调用
app\code\local\Zhlmmc\Helloworld\controllers\BlogController.php
 public function eavReadAction(){
             $eavModel = Mage::getModel (‘helloworld-eav/eavblogpost’);  // 需要引用模型的类实例化 Zhlmmc/Helloworld/Model/Eavblogpost.php
             $params = $this-> getRequest()->getParams ();
             echo(“Loading the blogpost with an ID of “. $params[‘id’ ].“<br/>”);
             $eavModel->load ($params[ ‘id’]);
             $data = $eavModel-> getData();
             var_dump ($data);
         }

        
         public function eavRead2Action (){
             $eavModel = Mage::getModel (‘helloworld-eav/eavblogpost’);   //需要引用模型的类实例化 Zhlmmc/Helloworld/Model/Eavblogpost.php
             echo get_class( $eavModel).“<br/>” ; 
         }
        
         public function eavPopulateEntriesAction () {
             for($i =0; $i<10 ;$i++) {  
                 $weblog2 = Mage:: getModel(‘helloworld-eav/eavblogpost’ );  // 需要引用模型的类实例化 Zhlmmc/Helloworld/Model/Eavblogpost.php
                 $weblog2->setTitle (‘This is a test ‘.$i );
                 $weblog2->save ();
             }  
             echo ‘Done’ ;
         }
        
         public function eavShowcollectionAction () {
             $weblog2 = Mage::getModel (‘helloworld-eav/eavblogpost’);  // 需要引用模型的类实例化 Zhlmmc/Helloworld/Model/Eavblogpost.php
             $entries = $weblog2 ->getCollection()-> addAttributeToSelect(‘title’ );      
             $entries->load ();
             foreach($entries as $entry)
             {
                 var_dump ($entry-> getData());
                 echo ‘<h1>’ .$entry-> getTitle().‘</h1>’ ;
             }
             echo ‘<br>Done<br>’ ;
         }


}



what is container1 and container2 in product view page in magento

These relate to the position in which the product’s custom options are displayed.

See app/code/core/Mage/Catalog/etc/config.xml:

<design>
    <options_container>
        <option1 translate="label">
            <value>container1</value>
            <label>Product Info Column</label>
        </option1>
        <option2 translate="label">
            <value>container2</value>
            <label>Block after Info Column</label>
        </option2>
    </options_container>
</design>

Here you can see that container1 relates to ‘Product Info Column’, while container2 is ‘Block after Info Column’. These values are describing where the custom options will be displayed on the product view page. You can set these values when editing a product in the Magento admin under the Design tab.

The layout blocks are defined in app/design/frontend/base/default/layout/catalog.xml:

<block type="core/template_facade" name="product.info.container1" as="container1">
    <action method="setDataByKey"><key>alias_in_layout</key><value>container1</value></action>
    <action method="setDataByKeyFromRegistry"><key>options_container</key><key_in_registry>product</key_in_registry></action>
    <action method="append"><block>product.info.options.wrapper</block></action>
    <action method="append"><block>product.info.options.wrapper.bottom</block></action>
</block>
<block type="core/template_facade" name="product.info.container2" as="container2">
    <action method="setDataByKey"><key>alias_in_layout</key><value>container2</value></action>
    <action method="setDataByKeyFromRegistry"><key>options_container</key><key_in_registry>product</key_in_registry></action>
    <action method="append"><block>product.info.options.wrapper</block></action>
    <action method="append"><block>product.info.options.wrapper.bottom</block></action>
</block>

And in app/design/frontend/base/default/template/catalog/product/view.phtml you will see two calls:

<?php echo $this->getChildChildHtml(‘container1’, ”, true, true) ?>
and
<?php echo $this->getChildChildHtml(‘container2’, ”, true, true) ?>

magento 事件监听

1.分发事件
Mage:: dispatchEvent (‘controller_action_predispatch_catalog_product_view_v’,array (‘1’=> ‘1’));
2.监听事件\
<frontend>
    <events>
        <controller_action_predispatch_catalog_product_view_v>
            <observers>
                <Newfrog_TierPriceRewrite_Model_Observer>
                    <class>
Newfrog_TierPriceRewrite_Model_Observer </class>
                    <method>
TierPriceRewrite </method>
                </Newfrog_TierPriceRewrite_Model_Observer>
            </observers>
        </controller_action_predispatch_catalog_product_view_v>
    </events>
</frontend>

mantis业务流程改造

antis 搭建好后默认的流程不能满足公司的需要,那么我们就需要调整这个业务流程,操作如下:
1.修改config_defaults_inc.php文件
$g_status_enum_string字段,增加一个选项,依据你设计的流程在添加合适的数值,例如,如果你是提交bug后被退回,可增加15:returned,
$g_status_enum_string= ’10:new,15:returned,20:feedback,30:acknowledged,40:confirmed,50:assigned,80:resolved,90:closed’;
找到这个数组 $g_status_colors ,增加你对应流程的颜色
如:’feedback’ => ‘#e3b7eb’,
2、若是你使用的简体中文还需要在mantis\lang目录中打开strings_chinese_simplified.txt文件,找到$s_status_enum_string字段,将对应的中文意思添加上去。如下:
$s_status_enum_string = ’10:新建,15:退回,20:反馈,30:认可,40:已确认,50:已分派,80:已解决,90:已关闭’;
3. 管理员重新登录,进入工作流管理,可以看到在已确认和已关闭之间多了一个状态:“退回”,再做一些相应的配置即可强制工作流经过这一状态,并将权限赋给即可。

php 中奖概率算法

我们先完成后台PHP的流程,PHP的主要工作是负责配置奖项及对应的中奖概率,当前端页面点击翻动某个方块时会想后台PHP发送ajax请求,那么后台PHP根据配置的概率,通过概率算法给出中奖结果,同时将未中奖的奖项信息一并以JSON数据格式发送给前端页面。先来看概率计算函数 1 function get

http://m.brogrammer.cn/article/id/MTk0NTQz.html

工厂模式

1.工厂模式是 实例化对象模式;
2.是实多态性的关键;
3.特征就是把 创建实例的工作与 使用实例的工作分开
你会建立一个专门生产Sample实例的工厂:
1
2
3
4
5
6
7
8
public class Factory{
    public static ISample creator(int which){
        if (which==1)
            return new SampleA();
        else if (which==2)
            return new SampleB();
    }
}

那么在你的程序中,如果要创建ISample的实列时候可以使用
iSample sampleA=Factory.creator(1);

php设计模式之命令模式

 命令模式
 将一个请求封装为一个对象从而使你可用不同的请求对客户进行参数化,对请求排除或记录请求日志,以及支持可取消的操作
<?php

class CommandNotFoundException extends Exception {}

class CommandFactory {
    private static $dir = 'commands' ;

    static function getCommand( $action ='Default' ) {
        if ( preg_match( '/\W/', $action ) ) {
            throw new Exception( "illegal characters in action") ;
        }
        $class = UCFirst (strtolower($action)). "Command"; 
        $file = self ::$dir. DIRECTORY_SEPARATOR ."$class .php";
        if ( ! file_exists( $file ) ) {
            throw new CommandNotFoundException( "could not find '$file '" );
        }
        require_once( $file );
        if ( ! class_exists( $class ) ) {
            throw new CommandNotFoundException( "no '$class' class located" ) ;
        }
        $cmd = new $class ();
        return $cmd;
    }
}

class Controller { //调用者 ,调用对应的命令并执行
    private $context;
    function __construct() {
        $this ->context = new CommandContext() ;
    }

    function getContext() {
        return $this ->context;
    }

    function process() {
        $cmd = CommandFactory::getCommand( $this->context ->get( 'action') ); //工厂模式的组合
        if ( ! $cmd->execute ( $this-> context ) ) {
            // handle failure
        } else {
            // success
            // dispatch view
        }
    }
}   




 // ------------- helper stuff
 class User{
    private $name;
    function __construct( $name ) {
        $this ->name = $name;
    }
}

class Registry {
    static function getMessageSystem() {
        return new MessageSystem() ;
    }
    static function getAccessManager() {
        return new AccessManager() ;
    }
}

class MessageSystem {
    function send( $mail , $msg, $topic ) {
        print "sending $mail: $topic : $msg\n" ;
        return true;
    }

    function getError() {
        return "move along now, nothing to see here";
    }
}

class AccessManager {
    function login( $user , $pass ) {
        $ret = new User( $user );
        return $ret;
    }

    function getError() {
        return "move along now, nothing to see here";
    }
}

class CommandContext {
    private $params = array() ;
    private $error = "";

    function __construct() {
        $this ->params = $_REQUEST;
    }

    function addParam( $key , $val ) {
        $this ->params[ $key]=$val ;
    }

    function get( $key ) {
        return $this ->params[ $key];
    }

    function setError( $error ) {
        $this ->error = $error;
    }

    function getError() {
        return $this ->error;
    }
}

$controller = new Controller() ;
$context = $controller-> getContext(); //new CommandContext()
$context ->addParam( 'action', 'feedback' ); //new CommandContext()::::$this->params[$key]=$val;
$context ->addParam( 'email', 'bob@bob.com' );
$context ->addParam( 'topic', 'my brain' );
$context ->addParam( 'msg', 'all about my brain' ) ;
$controller ->process() ;  //第一步返回类 ,再执行类的execute
print $context->getError ();

?>