0

in Magento 2.1.11 with PHP 7.0, I need to extend formatDate($date, $includeTime = true) method in Magento\Framework\Stdlib\DateTime and add third argument to it.

I created a new module and override this method by preference its class in di.xml:

<preference for="Magento\Framework\Stdlib\DateTime" type="MyVendor\MyModule\Framework\Stdlib\DateTime"/>

and MyVendor\MyModule\Framework\Stdlib\DateTime.php is:

namespace MyVendor\MyModule\Framework\Stdlib;

class DateTime extends \Magento\Framework\Stdlib\DateTime{

    public function formatDate($date, $includeTime = true, $myArg = false){

    ...}

}

But after use this method in my template file (order/recent.phtml) like this:

echo $block->formatDate(time(),true,true);

The third argument $myArg always is false!

What can I do for adding this third argument to this method!?

Thanks in advance.

1

If following Magento best practices, you cannot do this. Magento 2 prefers composition over inheritance. Best practice states that you should not extend and modify.

Additionally, the method's arguments are likely restricted by the rules set forth in an interface.

It sounds like the right solution for you would be a before, around, or after plugin, depending on what you would like to accomplish.

  • So, Magento is not that so flexible with it's core changing! :( – Mehran Zarei Apr 28 '18 at 14:42
  • 1
    @MehranZarei It's actually extremely flexible. Interfaces are used to set specific rules to ensure that your customizations ALWAYS work. You should really become familiar with Magento 2's "plugin" system, it is super helpful. Alan Storm has written some very good tutorials on how to use them. – Shawn Abramson Apr 28 '18 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.