docs: add explanation about a shared instance and parameters

This commit is contained in:
kenjis 2022-08-27 18:03:56 +09:00
parent 6234f0ed45
commit b8e0e64f39
No known key found for this signature in database
GPG Key ID: BD254878922AF198
2 changed files with 25 additions and 1 deletions

View File

@ -36,7 +36,7 @@ come in handy.
Instead of creating the instance ourself, we let a central class create an instance of the
class for us. This class is kept very simple. It only contains a method for each class that we want
to use as a service. The method typically returns a shared instance of that class, passing any dependencies
to use as a service. The method typically returns a **shared instance** of that class, passing any dependencies
it might have into it. Then, we would replace our timer creation code with code that calls this new class:
.. literalinclude:: services/002.php
@ -57,6 +57,15 @@ As many CodeIgniter classes are provided as services, you can get them like the
The ``$typography`` is an instance of the Typography class, and if you call ``\Config\Services::typography()`` again, you will get the exactly same instance.
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.
.. literalinclude:: services/015.php
Therefore, the parameter ``$options2`` for the ``$client2`` does not work. It is just ignored.
Getting a New Instance
======================
If you want to get a new instance of the Typography class, you need to pass ``false`` to the argument ``$getShared``:
.. literalinclude:: services/014.php

View File

@ -0,0 +1,15 @@
<?php
$options1 = [
'baseURI' => 'http://example.com/api/v1/',
'timeout' => 3,
];
$client1 = \Config\Services::curlrequest($options1);
$options2 = [
'baseURI' => 'http://another.example.com/api/v2/',
'timeout' => 10,
];
$client2 = \Config\Services::curlrequest($options2);
// $options2 does not work.
// $client2 is the exactly same instance as $client1.