mirror of
https://github.com/codeigniter4/CodeIgniter4.git
synced 2025-02-20 11:44:28 +08:00
docs: add explanation about a shared instance and parameters
This commit is contained in:
parent
6234f0ed45
commit
b8e0e64f39
@ -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
|
||||
|
15
user_guide_src/source/concepts/services/015.php
Normal file
15
user_guide_src/source/concepts/services/015.php
Normal 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.
|
Loading…
x
Reference in New Issue
Block a user