1

I have installed an extension and need to add a new function to it without editing the core extension files.

I need to add a function in this file/class: Vendor/vendor_name/module_name/block/Post/View.php

How is this done?

  • You can directly open the file and add your function, assume the need is in the template file, in the .phtml file you can use $block->myfunction(); – Krishna ijjada Feb 20 '17 at 13:57
  • Ok, yes my intention was to use the function in a template file. But I don't want to edit the extension "core" file so it could be overwritten on updates. I thought there was a way doing this within my theme? – ineluki Feb 20 '17 at 17:44
1

I think the best way to accomplish what you're after is to create a new module and then use the new modules's di.xml to set a preference for the file you want to add the function to, extend it, and then add your new function.

So say you've got Vendor/Module1 that you have View.php in and you want to add a function to it. Create Vendor/Module2 and then in Module2's etc/di.xml put

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="VENDOR\MODULE1\Block\Post\View"
                type="VENDOR\MODULE2\Block\Post\View" />
</config>

Then create your new Module 2 View.php and have it extend Module 1's View.php like

<?php

namespace VENDOR\MODULE2\Block\Post;

class View extends \VENDOR\MODULE1\Block\Post\View
{
    public function myAdditionalFunction()
    {
        echo "Hello world";
    }
}

Now you can update Module1 and not have to worry about your additional function getting overwritten in the update.

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.