官术网_书友最值得收藏!

  • Drupal 8 Module Development
  • Daniel Sipos
  • 399字
  • 2021-07-02 15:45:16

Service dependencies

In the preceding section, we created a form that allows administrators to set a custom salutation message to be shown on the page. This message was stored in a configuration object that we can now load in our HelloWorldSalutation service. So, let's do just that in a two-step process.

First, we will need to alter our service definition to give our service an argument--the Drupal 8 configuration factory (the service responsible for loading config objects). This is how our service definition should look:

 hello_world.salutation:
class: Drupal\hello_world\HelloWorldSalutation
arguments: ['@config.factory']

The addition is the argument's key, which is an array of service names proceeded by @. In this case, config.factory is the responsible service name, which if we check in the core.services.yml file, we will note that it maps to the Drupal\Core\Config\ConfigFactory class.

So, with this change, the HelloWorldSalutation class will be passed an instance of ConfigFactory. All we need to do now is to adjust our class to actually receive it:

  /**
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;

/**
* HelloWorldSalutation constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
*/
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}

There's nothing too complicated going on here. We added a constructor and set config factory in a property. We can now use this config factory to load our configuration object that we saved in the form. However, before we do that, we should also use the ConfigFactoryInterface class at the top of the file:

use Drupal\Core\Config\ConfigFactoryInterface;

Now, at the top of the getSalutation() method, we can add the following bit:

  $config = $this->configFactory->get('hello_world.custom_salutation');
$salutation = $config->get('salutation');
if ($salutation != "") {
return $salutation;
}

With the preceding code, we can load the configuration object we saved in the form, and from it, we request the salutation key, where if you remember, we stored our message. If there is a value in there, we will return it. Otherwise, the code will continue and our previous logic of time-based greeting apply.

So, now if we reload our initial page, the message we saved through the form should show up. If we then return to the form and remove the message, this page should default back to the original dynamic greeting. Neat, right?

Let's now take a look at how we can create a custom block that we can place anywhere we like and which will output the same thing as our page.

主站蜘蛛池模板: 苍梧县| 安阳市| 随州市| 马尔康县| 双桥区| 莆田市| 和平区| 和静县| 屯昌县| 额尔古纳市| 宁陵县| 巨鹿县| 乐业县| 朝阳区| 铅山县| 西藏| 磐石市| 焦作市| 龙川县| 岳普湖县| 安吉县| 连江县| 上蔡县| 图片| 卢湾区| 卢龙县| 高邑县| 东城区| 旬邑县| 长白| 阿拉善左旗| 泸水县| 施甸县| 茂名市| 虎林市| 林甸县| 海原县| 长顺县| 古田县| 乡宁县| 武平县|