Home
About
Search
🌐
English Română
  • Magento – Create a custom shopping cart price rule

    Citește postarea în română

    Mar 8, 2012 Magento observer shopping cart price rule
    Share on:

    This is not a tutorial about setting up a Shopping Cart Price Rule in Magento, but rather about implementing a new one.

    A new type of rule in Magento needs a couple of things:
    – modify the admin area to add the new rule using an observer for adminhtml_block_salesrule_actions_prepareform,
    – a way to apply the new rule using an observer for salesrule_validator_process.

    Let’s build an example. Let’s say there is a Shopping Cart Price Rule that offers different discounts according to the number of products in the cart. The value that’s going to be used for the discount increment ($step) will be calculated. The first product will not receive a discount, the second product will receive a discount of $step, the third product will have a discount of 2*$step, until the maximum discount value will be reached. The following products will have a maximum discount. Ex:
    Discount Amount = 50
    Discount Qty = 5
    Step = Discount Amount / Discount Qty = 10

    Discount outcome:
    – 0% prod 1
    – 10% prod 2
    …
    – 50% prod 6
    – 50% prod 7

    The first step is the module activation using the file: app/etc/modules/CP_ProductNrDiscount.xml

    1<?xml version="1.0" encoding="UTF-8"?>
    2<config>
    3    <modules>
    4        <CP_ProductNrDiscount>
    5            <active>true</active>
    6            <codePool>local</codePool>
    7        </CP_ProductNrDiscount>
    8    </modules>
    9</config>
    

    The first observer, adminhtml_block_salesrule_actions_prepareform, must be in the “adminhtml” section of the config, because it will involve the admin. This observer will have access to the admin form, in order to modify it.

    The second observer, salesrule_validator_process, can be in the “frontend” or “global” section of the config. If it’s in the frontend section, it will only apply to the frontend section. If it’s in the global section it will also apply to backend. Usually, global is necessary when there are actions on the cart in the backend.

     1<?xml version="1.0" encoding="UTF-8"?>
     2<config>
     3    <modules>
     4        <CP_ProductNrDiscount>
     5            <version>0.0.1</version>
     6        </CP_ProductNrDiscount>
     7    </modules>
     8    <global>
     9        <models>
    10            <productnrdiscount>
    11                <class>CP_ProductNrDiscount_Model</class>
    12            </productnrdiscount>
    13        </models>
    14        <events>
    15            <salesrule_validator_process>
    16                <observers>
    17                    <productnrdiscount>
    18                        <type>model</type>
    19                        <class>productnrdiscount/observer</class>
    20                        <method>salesruleValidatorProcess</method>
    21                    </productnrdiscount>
    22                </observers>
    23            </salesrule_validator_process>
    24        </events>
    25    </global>
    26    <adminhtml>
    27        <events>
    28            <adminhtml_block_salesrule_actions_prepareform>
    29            <observers>
    30                <productnrdiscount>
    31                    <type>model</type>
    32                    <class>productnrdiscount/observer</class>
    33                <method>adminhtmlBlockSalesruleActionsPrepareform</method>
    34                </productnrdiscount>
    35            </observers>
    36            </adminhtml_block_salesrule_actions_prepareform>
    37        </events>
    38    </adminhtml>
    39</config>
    

    As you can see above, there must be an Observer model that will have the two methods which modify the admin and apply the discount.

     1<?php
     2/**
     3 * Number of product discount module
     4 *
     5 * @author Claudiu Persoiu https://blog.claudiupersoiu.ro
     6 */
     7class CP_ProductNrDiscount_Model_Observer {
     8
     9    // The new rule type
    10    const PRODUCT_NR_DISCOUNT = 'product_nr_discount';
    11
    12    /**
    13     * Add the new rule type to the admin menu
    14     *
    15     * @param Varien_Event_Observer $observer
    16     */
    17    public function adminhtmlBlockSalesruleActionsPrepareform
    18              (Varien_Event_Observer $observer) {
    19        // Extract the form field
    20        $field = $observer->getForm()->getElement('simple_action');
    21        // Extract the field values
    22        $options = $field->getValues();
    23        // Add the new value
    24        $options[] = array(
    25            'value' => self::PRODUCT_NR_DISCOUNT,
    26            'label' => 'Product Number Discount'
    27        );
    28        // Set the field
    29        $field->setValues($options);
    30    }
    31
    32    /**
    33     * Apply the discount
    34     * The discount will be applied for at least 2 products increasing
    35     * with a "step" for each product, where "step" is
    36     * maximum discount / number of products.
    37     *
    38     * @param Varien_Event_Observer $observer
    39     */
    40    public function salesruleValidatorProcess(Varien_Event_Observer $observer) {
    41
    42        // $item typeof Mage_Sales_Model_Quote_Item
    43        $item = $observer->getEvent()->getItem();
    44        // $rule typeof Mage_SalesRule_Model_Rule
    45        $rule = $observer->getEvent()->getRule();
    46
    47        // Number of products
    48        $qty = $item->getQty();
    49
    50        // We must check the rule type in order to isolate our rule type
    51        if($rule->getSimpleAction() == self::PRODUCT_NR_DISCOUNT && $qty > 1) {
    52
    53            // Extract rule details
    54            $discountAmount = $rule->getDiscountAmount();
    55            $discountQty = $rule->getDiscountQty();
    56
    57            // Discount step
    58            $step = $discountAmount/$discountQty;
    59
    60            // Discount calculation
    61            $discount = 0;
    62            for($i = 1; $i < $qty; $i++) {
    63                $itemDiscount = $i * $step;
    64                // If the discount is bigger then the maximum discount
    65                // then the maximum discount is used
    66                if($itemDiscount > $discountAmount) {
    67                    $itemDiscount = $discountAmount;
    68                }
    69
    70                $discount += $itemDiscount;
    71            }
    72            // Effective discount
    73            $totalDiscountAmount = ($item->getPrice() * $discount)/100;
    74
    75            // Discount in percent for each item
    76            $item->setDiscountPercent($discount / $qty);
    77
    78            // Setting up the effective discount, basically this is the discount value
    79            $result = $observer->getResult();
    80            $result->setDiscountAmount($totalDiscountAmount);
    81            $result->setBaseDiscountAmount($totalDiscountAmount);
    82
    83        }
    84    }
    85
    86}
    

    This observer will run at each request if there are items in cart that for which the rule is applicable. If the discount should be applied only for specific products, there can be filtered using the rule’s “Conditions” tab, just as you would normally do.

  • PHP 5.4 was released!

    Citește postarea în română

    Mar 2, 2012 PHP PHP4 php5.4
    Share on:

    PHP 5.4 was released!

    Even though is already yesterday news… literally, yesterday 1 March was released.

    The complete list of changes is available on php.net.

    I’m sorry that we still don’t have scalar type hinting in this version. The only change to type hinting was the “callable” word was added, about which I’ve talked in the closure in PHP 5.4  blog.

    Another interesting thing is that this time register_globals and magic_quotes_gpc were really removed, so the old PHP 4 apps don’t get to be compatible anymore with the help of a couple of flags in php.ini.

    Also the hex2bin() function was added, of course is not that important, but is interesting that the  bin2hex() function existed since PHP 4. 🙂

  • Magento native stack trace

    Citește postarea în română

    Feb 25, 2012 debug Magento PHP stack trace
    Share on:

    There are moments when you need to see the stack trace, to know how a certain point was reached. There are two native functions for that in PHP: debug_backtrace() si debug_print_backtrace. The first one returns an array and the second will print the stack trace to the screen.

    The problem is that this functions must be customized for Magento, because it is very possible that when you’re running debug_backtrace()  you can run out of memory before you can send the output to a log file.

    Magento has a native function for that purpose: Varien_Debug::backtrace([bool $return = false], [bool $html = true], [bool $withArgs = true]). In order to send the resulting stacktrace to a log file you simply all it with:

    1Mage::log(Varien_Debug::backtrace(true, false));
    

    This technique is very useful when you need to see where an certain object is initialized, and what methods were executed up to that point.

  • PHP 5.4 – Closures the right way!

    Citește postarea în română

    Feb 11, 2012 anonymous functions closures PHP php5.3 php5.4
    Share on:

    The concept of closure was introduced in PHP 5.3, with the new “more traditional” syntax for anonymous functions.

    PHP 5.3

    In PHP 5.3, a closure will rely on the term “use”, which was passing the variables to the anonymous function, making it a closure.

    The problem is that the anonymous function will only be able to access the variables that have been passed with “use”. When it comes to objects, there are passed by reference by default, but scalar variables (int, string, etc.) are passed by value, as this is the default behavior in PHP 5+:

     1$scalar = 5;
     2
     3$closure = function () use ($scalar) {
     4     return 'Scalar: ' . $scalar . PHP_EOL;
     5};
     6
     7echo $closure(); // Scalar: 5
     8
     9$scalar = 7;
    10
    11echo $closure(); // Scalar: 5
    

    Another problem is that you cannot pass $this when the anonymous function is declared inside an object, so only the public method and properties can be accessed inside the closure.

    PHP 5.4

    In PHP 5.4 the keyword “use” is optional, and the entire environment where the function was created is available inside the function.

    The advantage is that when the anonymous function is created inside another function or method, the anonymous function has access to the environment where it was created, even after the execution of the environment is over. The objects from this environment will be unset, only after the last reference to the closure will be unset:

     1class testClass {
     2
     3        private $changeableVar = 1;
     4        private $bigVar;
     5
     6        public function __construct() {
     7                // Allocate a big variable so we can see the changes in memory
     8                $this->bigVar = str_repeat("BigWord", 5000);
     9        }
    10
    11        /**
    12         * A method that returns the closure
    13         */
    14        public function closure() {
    15
    16                return function () {
    17                        // Display the value of a private property of the object
    18                        echo 'Private property: ' . $this->changeableVar.PHP_EOL;
    19
    20                        // Change the value of a private property of the object
    21                        $this->changeableVar = 2;
    22                };
    23        }
    24
    25        /**
    26         * Method that displays a private property
    27         */
    28        public function showChangeableVar() {
    29                echo 'Private property in method: ' . $this->changeableVar.PHP_EOL;
    30        }
    31
    32}
    33
    34// Memory befor the objects is created
    35echo "Memory: " . memory_get_usage() . PHP_EOL; // Memory: 229896
    36
    37// Create object
    38$testObj = new testClass();
    39
    40// Create closure
    41$closure = $testObj->closure();
    42
    43// Execute closure
    44$closure(); // Private property: 1
    45
    46// Displaying the current value of the private property
    47$testObj->showChangeableVar(); // Private property in method: 2
    48
    49// Memory befor object will be unset
    50echo "Memory: ". memory_get_usage() . PHP_EOL; // Memory: 266240
    51
    52// Unset the object
    53unset($testObj);
    54
    55// Memory after the object was distroyed, there is no big difference in memory
    56echo "Memory: ". memory_get_usage() . PHP_EOL; // Memory: 266152
    57
    58// Run closure after the object in which it was created was unset
    59echo $closure(); // Private property: 2
    60
    61// Unset closure and with it the object environment
    62unset($closure);
    63
    64// Memotry after the las reference to the object (closure) is unset
    65echo "Memory: " . memory_get_usage() . PHP_EOL; // Memory: 230416
    

    Callable type hinting

    Another new feature introduced in PHP 5.4 regarding closures is the new “type hint”: “callable”. Actually callable is referring to any anonymous function, and even to a new way of calling a method of an object:

     1<?php
     2
     3// A function that uses type hinting
     4function typeHinting(callable $a) {
     5     echo $a() . PHP_EOL;
     6}
     7
     8// A closure
     9$closure = function () {
    10     return __FUNCTION__;
    11};
    12
    13// Call the type hinting function with the closure
    14typeHinting($closure); // {closure}
    15
    16class testClass {
    17     public function testMethod() {
    18          return __METHOD__;
    19     }
    20}
    21
    22// A mock object
    23$testObj = new testClass();
    24
    25// The new way of calling object methods
    26$objCallable = array($testObj, 'testMethod');
    27
    28// Call type hinting function with the new method calling way
    29typeHinting($objCallable); // testClass::testMethod
    

    I believe that only now we can really say that PHP supports closures, the right way!

  • Magento dead end – Breadcrumbs

    Citește postarea în română

    Feb 3, 2012 Magento PHP
    Share on:

    In one of my adventures in the Magento code. I’ve encountered the following problem: I had to add a link to the breadcrumb.

    As the documentation is not so great, after a little debugging (not a lot), I’ve got in to the core Mage_Page_Block_Html_Breadcrumbs.

    The method is quite self-explanatory: addCrumb($crumbName, $crumbInfo, $after = false). Since I was there, I took a look inside:

    1function addCrumb($crumbName, $crumbInfo, $after = false)
    2{
    3  $this->_prepareArray($crumbInfo, array('label', 'title', 'link', 'first', 'last', 'readonly'));
    4  if ((!isset($this->_crumbs[$crumbName])) || (!$this->_crumbs[$crumbName]['readonly'])) {
    5    $this->_crumbs[$crumbName] = $crumbInfo;
    6  }
    7  return $this;
    8}
    

    What’s interesting is the $after parameter, as you can see, even though it has a default value, is not used anywhere. The rest work’s as expected, probably this is why people don’t complain so much about it.

    • ««
    • «
    • 5
    • 6
    • 7
    • 8
    • 9
    • »
    • »»

Claudiu Perșoiu

Programming, technology and more
Read More

Recent Posts

  • Adding a slider to Tasmota using BerryScript
  • The future proof project
  • Docker inside wsl2
  • Moving away from Wordpress
  • Custom path for Composer cache
  • Magento2 and the ugly truth
  • A bit of PHP, Go, FFI and holiday spirit
  • How to make use of the Xiaomi Air Conditioning Companion in Home Assistant in only 20 easy steps!

PHP 49 MISCELLANEOUS 46 JAVASCRIPT 14 MAGENTO 7 MYSQL 7 BROWSERS 6 DESIGN PATTERNS 5 HOME AUTOMATION 2 LINUX-UNIX 2 WEB STUFF 2 GO 1

PHP 35 JAVASCRIPT 15 PHP5.3 11 MAGENTO 7 PHP6 7 MYSQL 6 PHP5.4 6 ZCE 6 CERTIFICARE 5 CERTIFICATION 5 CLOSURES 4 DESIGN PATTERNS 4 HACK 4 ANDROID 3
All tags
3D1 ADOBE AIR2 ANDROID3 ANGULAR1 ANONYMOUS FUNCTIONS3 BERRYSCRIPT1 BOOK1 BROWSER2 CARTE1 CERTIFICARE5 CERTIFICATION5 CERTIFIED1 CERTIFIED DEVELOPER1 CHALLENGE1 CHM1 CLASS1 CLI2 CLOSURES4 CODE QUALITY1 CODEIGNITER3 COFFEESCRIPT1 COLLECTIONS1 COMPOSER1 CSS1 DEBUG1 DESIGN PATTERNS4 DEVELOPER1 DEVELOPMENT TIME1 DOCKER2 DOCKER-COMPOSE1 DOUGLAS CROCKFORD2 ELEPHPANT2 FACEBOOK2 FFI1 FINALLY1 FIREFOX3 GAMES1 GENERATOR1 GO1 GOOGLE1 GOOGLE CHROME1 GOOGLE MAPS1 HACK4 HOMEASSISTANT2 HTML2 HTML HELP WORKSHOP1 HTML51 HUG1 HUGO1 INFORMATION_SCHEMA1 INI1 INTERNET EXPLORER3 IPV41 IPV61 ITERATOR2 JAVASCRIPT15 JQUERY1 LAMBDA1 LINUX1 MAGENTO7 MAGENTO22 MAP1 MINESWEEPER1 MOTIVATION1 MYSQL6 NGINX1 NODE.JS2 NOSQL1 OBSERVER3 OBSERVER PATTERN1 OOP1 OPERA1 OPTIMIZATION1 ORACLE1 PAGESPEED1 PAIR1 PARSE_INI_FILE1 PHONEGAP2 PHP35 PHP ELEPHANT2 PHP FOR ANDROID1 PHP-GTK1 PHP42 PHP53 PHP5.311 PHP5.46 PHP5.53 PHP5.61 PHP67 PHP7.41 PROGRAMMING1 REVIEW1 ROMANIAN STEMMER2 SAFARY1 SCALAR TYPE HINTING1 SCHEME1 SET1 SHOPPING CART PRICE RULE1 SINGLETON1 SOAP1 SPL2 SQLITE1 SSH1 STACK TRACE1 STDERR1 STDIN1 STDOUT1 SUN1 SYMFONY2 TASMOTA1 TEST TO SPEECH1 TITANIUM2 TRAITS1 TTS1 UBUNTU1 UNICODE2 UTF-82 VECTOR1 WEBKIT1 WINBINDER1 WINDOWS2 WORDPRESS1 WSL21 YAHOO3 YAHOO MAPS1 YAHOO OPEN HACK1 YSLOW1 YUI1 ZCE6 ZCE5.31 ZEND3 ZEND FRAMEWORK3
[A~Z][0~9]

Copyright © 2008 - 2024 CLAUDIU PERȘOIU'S BLOG. All Rights Reserved