Skip to content

Commit b8e0e64

Browse files
committed
docs: add explanation about a shared instance and parameters
1 parent 6234f0e commit b8e0e64

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

user_guide_src/source/concepts/services.rst

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ come in handy.
3636

3737
Instead of creating the instance ourself, we let a central class create an instance of the
3838
class for us. This class is kept very simple. It only contains a method for each class that we want
39-
to use as a service. The method typically returns a shared instance of that class, passing any dependencies
39+
to use as a service. The method typically returns a **shared instance** of that class, passing any dependencies
4040
it might have into it. Then, we would replace our timer creation code with code that calls this new class:
4141

4242
.. literalinclude:: services/002.php
@@ -57,6 +57,15 @@ As many CodeIgniter classes are provided as services, you can get them like the
5757

5858
The ``$typography`` is an instance of the Typography class, and if you call ``\Config\Services::typography()`` again, you will get the exactly same instance.
5959

60+
The Services typically return a **shared instance** of the class. The following code creates a ``CURLRequest`` instance at the first call. And the second call returns the exactly same instance.
61+
62+
.. literalinclude:: services/015.php
63+
64+
Therefore, the parameter ``$options2`` for the ``$client2`` does not work. It is just ignored.
65+
66+
Getting a New Instance
67+
======================
68+
6069
If you want to get a new instance of the Typography class, you need to pass ``false`` to the argument ``$getShared``:
6170

6271
.. literalinclude:: services/014.php
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
$options1 = [
4+
'baseURI' => 'http://example.com/api/v1/',
5+
'timeout' => 3,
6+
];
7+
$client1 = \Config\Services::curlrequest($options1);
8+
9+
$options2 = [
10+
'baseURI' => 'http://another.example.com/api/v2/',
11+
'timeout' => 10,
12+
];
13+
$client2 = \Config\Services::curlrequest($options2);
14+
// $options2 does not work.
15+
// $client2 is the exactly same instance as $client1.

0 commit comments

Comments
 (0)