[英]Which is better way to initialise Component in Yii2?
I have created one component in Yii2 and extends it with yii\\base\\Component
. 我在Yii2中创建了一个组件,并使用
yii\\base\\Component
对其进行了扩展。
Now, I want to initialise the component that I have created which can be done in two ways 现在,我想初始化我创建的组件,可以通过两种方式完成
Using new
: 使用
new
:
$sampleClass = new SampleClass();
Putting Component in config file: 将组件放入配置文件中:
'sampleClass' => [ 'class' => 'app\\components\\SampleClass', ],
and accessing it like Yii::$app->sampleClass
. 并像
Yii::$app->sampleClass
那样访问它。
What is difference between them and which is better way to initialise component? 它们之间有什么区别,哪种是初始化组件的更好方法?
It mostly depends on your needs. 这主要取决于您的需求。 Defining component in config and using it as
Yii::$app->sampleClass
creates one instance which can be easily configured at config level and shared across project. 在config中定义组件并将其用作
Yii::$app->sampleClass
创建一个实例,该实例可以在config级别轻松配置并在整个项目中共享。 The perfect examples are DB connection or URL manager - usually you want to use the same instance of these components in multiple places, and you want to be able to easily configure them. 完美的示例是数据库连接或URL管理器-通常,您希望在多个位置使用这些组件的相同实例,并且希望能够轻松配置它们。 Defining them in config and using as
Yii::$app->component
is natural choice in Yii (although it is bad practice overall and using Yii::$app
as static service locator may be problematic in big applications). 在config中定义它们并将其用作
Yii::$app->component
在Yii中是很自然的选择(尽管总体上是不好的做法,在大型应用程序中使用Yii::$app
作为静态服务定位器可能会出现问题)。
Using new
keyword or Yii::createObject()
is better option if you don't want to share component or you want to pass it as dependency directly. 如果您不想共享组件或希望直接将其作为依赖项传递,则使用
new
关键字或Yii::createObject()
是更好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.