obj."/> obj.">

Maison  >  Article  >  cadre php  >  ThinkPHP joue avec sa propre classe de conteneur

ThinkPHP joue avec sa propre classe de conteneur

咔咔
咔咔original
2020-10-12 12:24:071862parcourir
"

Cet article implémentera une classe de conteneur simple

"

5 , jouez avec votre propre classe conteneur

À ce stade, nous modifions le fichier Personne

Ajoutez un constructeur et attribuez les paramètres à l'aide du constructeur Dans l'achat. méthode, il n'est pas nécessaire de transmettre des paramètres, utilisez simplement this->obj.

ThinkPHP joue avec sa propre classe de conteneurSi vous exécutez toujours la route dependency directement à ce moment-là, l'erreur suivante sera signalée parce que le constructeur dans Person a un paramètre, mais nous ne l'avons pas transmis.

ThinkPHP joue avec sa propre classe de conteneurÀ ce stade, vous devez modifier une chose, qui est de passer l'instance Car comme paramètre lors de l'instanciation de Person et il n'y aura aucun problème.

ThinkPHP joue avec sa propre classe de conteneur
Insérer la description de l'image ici

Mais vous découvrirez quel code se trouve ci-dessus Ce qui était à l'origine quelques simples lignes de code est devenu compliqué comme ça. , cette fois a déjà fait plus de mal que de bien. Quelle que soit la qualité du modèle de conception, l'utilisation aveugle est également un fardeau pour le projet.

C'est donc à ce moment-là que la réflexion arrive. La réflexion est brièvement présentée ci-dessus, alors assurez-vous de la lire ! Les articles sont tous liés entre eux.

Code d'optimisation de combat de réflexion

Le code optimisé final est comme ceci. Ensuite, nous analyserons brièvement ce code.

  • Sur la base du code précédent, seule la méthode get dans kaka/container/Container.phpcette classe a été modifiée
  • Pour déterminer si la personne nommée est dans le conteneur
  • Utilisez l'interface de réflexion, puis récupérez le constructeur de la classe person transmis dans
  • Si la personne n'a pas de constructeur, renvoyez simplement l'instance de personne directement
  • S'il existe un constructeur de personne, alors obtenez la méthode du constructeur de personne
  • Parce que les paramètres. du constructeur dans la classe personne ne sera pas seulement limité à un
  • , donc une boucle est nécessaire pour obtenir l'objet de chaque paramètre
  • Enfin, utilisez l'interface newInstanceArgs réfléchie pour créer l'instance correspondante
<span style="display: block; background: url(https://my-wechat.mdnice.com/point.png); height: 30px; width: 100%; background-size: 40px; background-repeat: no-repeat; background-color: #282c34; margin-bottom: -7px; border-radius: 5px; background-position: 10px 10px;"></span><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; font-size: 12px; -webkit-overflow-scrolling: touch; padding-top: 15px; background: #282c34; border-radius: 5px;"><span class="hljs-meta" style="color: #61aeee; line-height: 26px;"><?php</span><br/><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">/**<br/> * Created by PhpStorm.<br/> * User: 咔咔<br/> * Date: 2020/9/21<br/> * Time: 19:04<br/> */</span><br/><br/><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">namespace</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">container</span>;<br/><br/><br/><span class="hljs-class" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">class</span> <span class="hljs-title" style="color: #e6c07b; line-height: 26px;">Container</span><br/></span>{<br/>    <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">/**<br/>     * 存放容器<br/>     * <span class="hljs-doctag" style="color: #c678dd; line-height: 26px;">@var</span> array<br/>     */</span><br/>    <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">public</span> $instances = [];<br/><br/>    <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">/**<br/>     * 容器的对象实例<br/>     * <span class="hljs-doctag" style="color: #c678dd; line-height: 26px;">@var</span> array<br/>     */</span><br/>    <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">protected</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">static</span> $instance;<br/><br/>    <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">/**<br/>     * 定义一个私有的构造函数防止外部类实例化<br/>     * Container constructor.<br/>     */</span><br/>    <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">private</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">function</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">__construct</span><span class="hljs-params" style="line-height: 26px;">()</span> </span>{<br/><br/>    }<br/><br/>    <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">/**<br/>     * 获取当前容器的实例(单例模式)<br/>     * <span class="hljs-doctag" style="color: #c678dd; line-height: 26px;">@return</span> array|Container<br/>     */</span><br/>    <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">public</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">static</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">function</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">getInstance</span> <span class="hljs-params" style="line-height: 26px;">()</span><br/>    </span>{<br/>        <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">if</span>(is_null(<span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">self</span>::$instance)){<br/>            <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">self</span>::$instance = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">new</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">self</span>();<br/>        }<br/><br/>        <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">self</span>::$instance;<br/>    }<br/><br/>    <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">public</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">function</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">set</span> <span class="hljs-params" style="line-height: 26px;">($key,$value)</span><br/>    </span>{<br/>        <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">$this</span>->instances[$key] = $value;<br/>    }<br/><br/>    <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">/**<br/>     * User : 咔咔<br/>     * Notes: 获取容器里边的实例  使用反射<br/>     * Time :2020/9/21 22:04<br/>     * <span class="hljs-doctag" style="color: #c678dd; line-height: 26px;">@param</span> $key<br/>     * <span class="hljs-doctag" style="color: #c678dd; line-height: 26px;">@return</span> mixed<br/>     */</span><br/>    <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">public</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">function</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">get</span> <span class="hljs-params" style="line-height: 26px;">($key)</span><br/>    </span>{<br/>        <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">if</span>(!<span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">empty</span>(<span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">$this</span>->instances[$key])){<br/>            $key = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">$this</span>->instances[$key];<br/>        }<br/><br/>        $reflect = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">new</span> \ReflectionClass($key);<br/>        <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">// 获取类的构造函数</span><br/>        $c = $reflect->getConstructor();<br/>        <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">if</span>(!$c){<br/>            <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">new</span> $key;<br/>        }<br/><br/>        <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">// 获取构造函数的参数</span><br/>        $params = $c->getParameters();<br/>        <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">foreach</span> ($params <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> $param) {<br/>       <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">/**<br/>             ReflectionClass Object<br/>            (<br/>                [name] => container\dependency\Car<br/>            )<br/>             */</span><br/>            $class = $param->getClass();<br/>            <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">if</span>(!$class){<br/><br/>            }<span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">else</span>{<br/>                <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">// container\dependency\Car</span><br/>                $args[] = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">$this</span>->get($class->name);<br/>            }<br/>        }<br/>        <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;">// 从给出的参数创建一个新的类实例</span><br/>        <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> $reflect->newInstanceArgs($args);<br/>    }<br/>}<br/></code>

ThinkPHP joue avec sa propre classe de conteneurFichierapplication/index/controller/Container.phpVoici les changements après modification

ThinkPHP joue avec sa propre classe de conteneur Question 1 : Que signifie le paramètre Car dans kaka/container/dependency/Person.php

Ce problème est en fait très simple. Vous pouvez voir que cette Car est le fichier Car.php dans le même répertoire. Vous pouvez le comprendre directement sous forme de fichiers sous le même espace de noms.

ThinkPHP joue avec sa propre classe de conteneurQuestion 2 : Fichier application/index/controller/Container.phpPourquoi la méthode buy peut-elle être appelée directement ?

Regardez d'abord la valeur de obj. L'objet renvoyé contient déjà la classe Car. exemple C'est fait, donc pas besoin de l'instancier, vous pouvez appeler directement la méthode d'achat, car les paramètres seront passés directement

ThinkPHP joue avec sa propre classe de conteneur
Insérer la description de l'image ici

ThinkPHP joue avec sa propre classe de conteneurCe qui précède est un simple conteneur implémenté par Kaka. Si vous ne comprenez pas ou si vous avez des questions, vous pouvez répondre directement dans la zone de commentaire.

L'étape suivante consiste à analyser les conteneurs dans le framework et à les remonter jusqu'à la cause première, étape par étape.

«

La persévérance dans l'apprentissage, la persévérance dans les blogs et la persévérance dans le partage sont les convictions auxquelles Kaka a toujours adhéré depuis sa carrière. J'espère que les articles de Kaka dans l'immense Internet. Je peux vous apporter un peu d'aide Silk. Je m'appelle Kaka, à la prochaine fois.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn