Magento 2 After plugin with parameter
문제
I am trying to implement after plugin to the following method.
public function getCategoryUrl($category)
{
if ($category instanceof ModelCategory) {
return $category->getUrl();
}
return $this->_categoryFactory->create()->setData($category->getData())->getUrl();
}
Please note the $category
parameter passed to the above method.
As the resolution, I have implemented below code.
public function afterGetCategoryUrl(\Magento\Catalog\Helper\Category $subject, $result)
{
return $result;
}
Now, my question is: How do I get the $category
parameter passed in parent method to my plugin? I just want to modify result based on the certain value in $category
object.
해결책
If you need input parameters and you also need to change output, you should use an around plugin, not an after plugin:
public function aroundGetCategoryUrl(
\Magento\Catalog\Helper\Category $subject,
\Closure $proceed,
$category
) {
...
// Do your stuffs here, now you have $category
// If you need you can call the original method with:
// $proceed($category);
...
return $something;
}
I your case it could be something like this:
public function aroundGetCategoryUrl(
\Magento\Catalog\Helper\Category $subject,
\Closure $proceed,
$category
) {
$originalResult = $proceed($category);
if (...) {
...
return $otherResult;
}
return $originalResult;
}
Just a note:
Please notice that if you are going to change an internal behaviour, a preference could be a better option that a plugin. It depends on what you are going to do.
다른 팁
Since Magento 2.2 it is possible to have input parameters in after plugin
namespace My\Module\Plugin;
class AuthLogger
{
private $logger;
public function __construct(\Psr\Log\LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @param \Magento\Backend\Model\Auth $authModel
* @param null $result
* @param string $username
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterLogin(\Magento\Backend\Model\Auth $authModel, $result, $username)
{
$this->logger->debug('User ' . $username . ' signed in.');
}
}
See Magento documentation for details https://devdocs.magento.com/guides/v2.2/extension-dev-guide/plugins.html#after-methods