Shopware是可扩展和可定制的, 至少这是框架背后的主要思想。有时你需要从自己的插件中扩展另一个插件, 在本文中特别是另一个插件的模型(Doctrine Entities)。就其本身而言(除非目标实体不允许对其进行扩展, 请参见学说继承), 从理论上讲这没什么大不了的。
例如, 假设存在一个模型, 即SwagThirdParty插件的Person, 我们想在自己的插件中扩展该模型。扩展的新模型如下所示:
<?php
namespace OurCodeWorldMyPlugin\Models;
use Doctrine\ORM\Mapping as ORM;
use Shopware\Components\Model\ModelEntity;
use Doctrine\Common\Collections\ArrayCollection;
// Model Of the Third Party Plugin
use Shopware\CustomModels\SwagThirdPartyPlugin\Person;
// Our new Model in our plugin that extends the model from another plugin
class Programmer extends Person
{
// ... content of the class ... //
}
如你所见, 该模型要求执行Person模型, 但是在某些情况下, 在通过命令行或插件管理器安装插件的过程中, 你可能会发现一个异常, 指出该Person模型不存在, 尽管SwagThirdPartyPlugin存在并且已经安装。
解
问题在于, 确实, 在你自己的插件安装期间该模型将不存在。通常仅在使用命令行(Shopware CLI工具)安装/重新安装插件时才会发生这种情况, 因为在此环境中, 将在没有其他已安装第三方插件上下文的情况下安装你的插件。要解决此问题, 你只需要注册插件的模型, 即可在插件的安装事件期间手动检索它们。
打开你插件的PHP文件(Bootstrap文件), 在我们的例子中为OurCodeWorldMyPlugin.php(根文件夹), 然后将新的私有方法registerThirdPartyPluginModels添加到该类中:
<?php
namespace OurCodeWorldMyPlugin;
use Shopware\Components\Plugin;
use Shopware\Components\Plugin\Context\ActivateContext;
use Shopware\Components\Plugin\Context\DeactivateContext;
use Shopware\Components\Plugin\Context\InstallContext;
use Shopware\Components\Plugin\Context\UninstallContext;
use Doctrine\ORM\Tools\SchemaTool;
// Use Models
use OurCodeWorldMyPlugin\Models\Programmer;
class OurCodeWorldMyPlugin extends Plugin
{
/**
* During the installation of our plugin, update the schema.
*
* @param InstallContext $context
*/
public function install(InstallContext $context)
{
// Register models of the third party plugin before registering ours
$this->registerThirdPartyPluginModels("SwagThirdPartyPlugin");
// Now you shouldn't get an exception when you try to register your new models
// during the rest of your code here ....
}
/**
* Register Models of the third party plugin before proceding with the mapping.
*
* Note: this adds a reference to all the models of the plugin with the given name
*/
private function registerThirdPartyPluginModels($thirdPartyPluginName)
{
try {
// As our plugin modifies a model from an external plugin, we need to retrieve the plugin
$plugin = Shopware()->Container()->get('shopware.plugin_manager')->getPluginBootstrap(
Shopware()->Container()->get('shopware.plugin_manager')->getPluginByName($thirdPartyPluginName)
);
// Register Models of the SwagThirdPartyPlugin, which give us access to its models
// during the generation of the schema for your new models.
$plugin->registerCustomModels();
} catch (\Exception $e) {}
}
}
如你所见, 新方法按其名称注册了插件的所有模型。你需要在导入新模型的代码段中运行该方法, 该模型需要第三方插件的模型(在本例中为Programmer), 否则你将看到异常。
编码愉快!
评论前必须登录!
注册