@@ -84,30 +84,41 @@ Next, define a new service for that class.
8484
8585 # app/config/services.yml
8686 services :
87- # keep your service names short
88- app.slugger :
89- class : AppBundle\Utils\Slugger
87+ # ...
88+
89+ # use the class name as the service id
90+ AppBundle\Utils\Slugger :
91+ public : false
92+
93+ .. note ::
9094
91- Traditionally, the naming convention for a service involved following the
92- class name and location to avoid name collisions. Thus, the service
93- *would have been * called ``app.utils.slugger ``. But by using short service names,
94- your code will be easier to read and use.
95+ If you're using the :ref: `default services.yml configuration <service-container-services-load-example >`,
96+ the class is auto-registered as a service.
97+
98+ Traditionally, the naming convention for a service was a short, but unique
99+ snake case key - e.g. ``app.utils.slugger ``. But for most services, you should now
100+ use the class name.
95101
96102.. best-practice ::
97103
98- The name of your application's services should be as short as possible ,
99- but unique enough that you can search your project for the service if
100- you ever need to .
104+ The id of your application's services should be equal to their class name ,
105+ except when you have multiple services configured for the same class (in that
106+ case, use a snake case id) .
101107
102108Now you can use the custom slugger in any controller class, such as the
103109``AdminController ``:
104110
105111.. code-block :: php
106112
107- public function createAction(Request $request)
113+ use AppBundle\Utils\Slugger;
114+
115+ public function createAction(Request $request, Slugger $slugger)
108116 {
109117 // ...
110118
119+ // you can also fetch a public service like this, but is not the best-practice
120+ // $slugger = $this->get('app.slugger');
121+
111122 if ($form->isSubmitted() && $form->isValid()) {
112123 $slug = $this->get('app.slugger')->slugify($post->getTitle());
113124 $post->setSlug($slug);
@@ -116,6 +127,16 @@ Now you can use the custom slugger in any controller class, such as the
116127 }
117128 }
118129
130+ Services can also be :ref: `public or private <container-public >`. If you use the
131+ :ref: `default services.yml configuration <service-container-services-load-example >`,
132+ all services are private by default.
133+
134+ .. best-practice ::
135+
136+ Services should be ``private `` whenever possible. This will prevent you from
137+ accessing that service via ``$container->get() ``. Instead, you will need to use
138+ dependency injection.
139+
119140Service Format: YAML
120141--------------------
121142
0 commit comments