Slim studied Note 5's dependency on the injection container (below)

In the previous section, we learned about several necessary methods for implementing the ArrayAccess interface in the Pi...

In the previous section, we learned about several necessary methods for implementing the ArrayAccess interface in the Pimple container. In this section, we will learn about other methods of PimpleContainer.  

/** * Mark callable object as factory service * Marks a callable as being a factory service. * * @param callable $callable A service definition to be used as a factory * * @return callable The passed callable * * @throws ExpectedInvokableException Service definition has to be a closure or an invokable object */ public function factory($callable) { if (!method_exists($callable, '__invoke')) { throw new ExpectedInvokableException('Service definition is not a Closure or invokable object.'); } // As we have seen, the factories property is splstorage, and you can use attach to bind objects $this->factories->attach($callable); return $callable; }
Why call the object to serve the factory? Previously, we learned from offsetGet that when the service is loaded for the first time, the execution result of the closure function will be stored in $values [] and the native closure will be stored in $rows (); the value stored in $values[$id] can be directly returned in the second call. But what if we want the service to be reloaded every time? Ha ha, you must have thought that the factory function will be called.

"By default, Pimple returns the same instance each time it gets a service. If you want to return different instances for all calls, wrap the anonymous function with the factory() method

/** * Prohibit a service from being called * Protects a callable from being interpreted as a service. * * This is useful when you want to store a callable as a parameter. * * @param callable $callable A callable to protect from being evaluated * * @return callable The passed callable * * @throws ExpectedInvokableException Service definition has to be a closure or an invokable object */ public function protect($callable) { if (!method_exists($callable, '__invoke')) { throw new ExpectedInvokableException('Callable is not a Closure or invokable object.'); } $this->protected->attach($callable); return $callable; }

Today's content is a little short, short is short, but it is also a knowledge point, ha ha.

2 July 2020, 12:02 | Views: 6343

Add new comment

For adding a comment, please log in
or create account

0 comments