What is the sense of naming invokables like classes?

前端 未结 3 1811
眼角桃花
眼角桃花 2021-02-04 21:44

I\'m going trough ZfcUser to learn more about modules in Zend Framework 2. In the Module.php you can see

\'invokables\' => array(
  \'ZfcUser\\Authentication\         


        
3条回答
  •  既然无缘
    2021-02-04 21:54

    In contrary of the other answers, I can state that there IS a convention, which is to use fully qualified class names for service names wherever possible (and fake class names where the service is virtual and instance of another class).

    If the problem is just about how ZfcUser does it, I can tell you that ZfcUser is not state of the art (currently 0.1.*) and needs a rewrite. You could look at BjyAuthorize for a better example.

    I use either the FQCN (Fully Qualified Class Name) of the class that is defined as a service, or the FQCN of the interface it implements, which helps avoiding that the user consuming the service uses API not specified in the interface, and just in the implementing class.

    Also, consider that it makes no real difference if you use \ or _ or lowercase or uppercase service names, since everything is normalized in the service manager. That basically means that zfcuser_service_user or ZfcUser\Service\User are the same.

    To recap, here's a good practice you could follow:

    'invokables' => array(
        // interface FQCN
        'Namespace\MyInterface' => 'Namespace\MyImplementation',
    
        // no interface available
        'Namespace\ClassName'   => 'Namespace\ClassName',
    
        // no interface nor own implementation available (similar to an alias)
        'Namespace\MyStuff'     => 'OtherNamespace\Stuff',
    ),
    

    This is both easy to remember and allows end-users of your service to look for Namespace\MyInterface and find what they were looking for.

    Use it also for factories and for services spawned from abstract classes if possible, since it makes things easier to remember for everyone.

提交回复
热议问题