Drupal之Controller与Services

What

A service is an object that gets instantiated by a Service Container and is used to handle operations in a reusable way, for example, performing calculations and interacting with the database, an external API, or any number of things. Moreover, it can take dependencies (other services) and use them to help out. Services are a core part of the dependency injection (DI) principle that is commonly used in modern PHP applications and in Drupal 8.
说白了就是MVC的Service层,处理业务逻辑。

How

  1. 定义自己的Services
    在src目录下建立class(如同写Controller类似)
    e.g.
namespace Drupal\hello_world;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class HelloWorldSalutation {
  use StringTranslationTrait;
  public function getSalutation() {    
    $time = new \DateTime();
    if ((int) $time->format('G') >= 06 && (int) $time->format('G') < 12) { 
     return $this->t('Good morning world');
    }
    if ((int) $time->format('G') >= 12 && (int) $time->format('G') < 18) {
      return $this->t('Good afternoon world');
    }
    if ((int) $time->format('G') >= 18) {
      return $this->t('Good evening world');
    }
  }
}
  1. 在自定义module中建立*.services.yml文件
services:  
  hello_world.salutation: 
    class: Drupal\hello_world\HelloWorldSalutation

意思是起一个key: "hello_world.salutation"。将来要通过这个key找到对应的class: Drupal\hello_world\HelloWorldSalutation。

  1. 使用。
    使用分为两种方式,一种是动态加载,在需要的时候引进来。另一种则是在构造函数和create方法里面将service注入。
  • statically
$service = \Drupal::service('hello_world.salutation')
  • injected
/**
 * @var \Drupal\hello_world\HelloWorldSalutation
 */  
protected $salutation;
 /**
  * HelloWorldController constructor.   
  *   
  * @param \Drupal\hello_world\HelloWorldSalutation $salutation   
  */  
public function __construct(HelloWorldSalutation $salutation) {    
  $this->salutation = $salutation;  
}
  /**   
   * {@inheritdoc}   
   */
 public static function create(ContainerInterface $container) {    
   return new static(      
     $container->get('hello_world.salutation')    
   );  
 } 

Tips:
引入Services,引入容器接口

use Drupal\hello_world\HelloWorldSalutation;
use Symfony\Component\DependencyInjection\ContainerInterface; 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,552评论 5 6
  • “哎,,你们没一起回家啊?” “嗯,是呢。” “毕竟是亲兄弟诶~你们两个简直真的完全长的一模一样诶!” “一样吗?...
    纯牛奶月亮阅读 181评论 0 0
  • 当我打开那年发给你的电子邮件,感觉那时的我真是幼稚,一个还没经历过爱情,不懂的什么是真正爱情的儒生,竟给爱情下了那...
    外婆树的伊甸园阅读 219评论 0 0
  • 最近腾讯视频单独为会员推送由《欲望都市》凯莉重回银幕又一巨作《Divorec》离婚,由此引发单独花了几天业余时间把...
    她可以微笑阅读 417评论 0 3