3v4l.org

run code in 300+ PHP versions simultaneously
<?php namespace RefactoringGuru\FactoryMethod\Conceptual; /** * Паттерн Фабричный Метод * * Назначение: Определяет общий интерфейс для создания объектов в суперклассе, * позволяя подклассам изменять тип создаваемых объектов. */ /** * Класс Создатель объявляет фабричный метод, который должен возвращать объект * класса Продукт. Подклассы Создателя обычно предоставляют реализацию этого * метода. */ abstract class Creator { /** * Обратите внимание, что Создатель может также обеспечить реализацию * фабричного метода по умолчанию. */ abstract public function factoryMethod(): Product; /** * Также заметьте, что, несмотря на название, основная обязанность Создателя * не заключается в создании продуктов. Обычно он содержит некоторую базовую * бизнес-логику, которая основана на объектах Продуктов, возвращаемых * фабричным методом. Подклассы могут косвенно изменять эту бизнес-логику, * переопределяя фабричный метод и возвращая из него другой тип продукта. */ public function someOperation(): string { // Вызываем фабричный метод, чтобы получить объект-продукт. $product = $this->factoryMethod(); // Далее, работаем с этим продуктом. $result = "Creator: creator's code has just worked with " . $product->operation(); return $result; } } /** * Конкретные Создатели переопределяют фабричный метод для того, чтобы изменить * тип результирующего продукта. */ class ConcreteCreator1 extends Creator { /** * Обратите внимание, что сигнатура метода по-прежнему использует тип * абстрактного продукта, хотя фактически из метода возвращается конкретный * продукт. Таким образом, Создатель может оставаться независимым от * конкретных классов продуктов. */ public function factoryMethod(): Product { return new ConcreteProduct1(); } } class ConcreteCreator2 extends Creator { public function factoryMethod(): Product { return new ConcreteProduct2(); } } /** * Интерфейс Продукта объявляет операции, которые должны выполнять все * конкретные продукты. */ interface Product { public function operation(): string; } /** * Конкретные Продукты предоставляют различные реализации интерфейса Продукта. */ class ConcreteProduct1 implements Product { public function operation(): string { return "{Result of the ConcreteProduct1}"; } } class ConcreteProduct2 implements Product { public function operation(): string { return "{Result of the ConcreteProduct2}"; } } /** * Клиентский код работает с экземпляром конкретного создателя, хотя и через его * базовый интерфейс. Пока клиент продолжает работать с создателем через базовый * интерфейс, вы можете передать ему любой подкласс создателя. */ function clientCode(Creator $creator) { // ... echo "Client: I'm not aware of the creator's class, but it still works.\n" . $creator->someOperation(); // ... } /** * Приложение выбирает тип создателя в зависимости от конфигурации или среды. */ echo "App: Launched with the ConcreteCreator1.\n"; clientCode(new ConcreteCreator1()); echo "\n\n"; echo "App: Launched with the ConcreteCreator2.\n"; clientCode(new ConcreteCreator2());
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  (null)
number of ops:  16
compiled vars:  none
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   81     0  E >   DECLARE_CLASS                                            'refactoringguru%5Cfactorymethod%5Cconceptual%5Cconcreteproduct1'
   89     1        DECLARE_CLASS                                            'refactoringguru%5Cfactorymethod%5Cconceptual%5Cconcreteproduct2'
  113     2        ECHO                                                     'App%3A+Launched+with+the+ConcreteCreator1.%0A'
  114     3        INIT_NS_FCALL_BY_NAME                                    'RefactoringGuru%5CFactoryMethod%5CConceptual%5CclientCode'
          4        NEW                                              $0      'RefactoringGuru%5CFactoryMethod%5CConceptual%5CConcreteCreator1'
          5        DO_FCALL                                      0          
          6        SEND_VAR_NO_REF_EX                                       $0
          7        DO_FCALL                                      0          
  115     8        ECHO                                                     '%0A%0A'
  117     9        ECHO                                                     'App%3A+Launched+with+the+ConcreteCreator2.%0A'
  118    10        INIT_NS_FCALL_BY_NAME                                    'RefactoringGuru%5CFactoryMethod%5CConceptual%5CclientCode'
         11        NEW                                              $3      'RefactoringGuru%5CFactoryMethod%5CConceptual%5CConcreteCreator2'
         12        DO_FCALL                                      0          
         13        SEND_VAR_NO_REF_EX                                       $3
         14        DO_FCALL                                      0          
         15      > RETURN                                                   1

Function refactoringguru%5Cfactorymethod%5Cconceptual%5Cclientcode:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  RefactoringGuru\FactoryMethod\Conceptual\clientCode
number of ops:  6
compiled vars:  !0 = $creator
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
  102     0  E >   RECV                                             !0      
  106     1        INIT_METHOD_CALL                                         !0, 'someOperation'
          2        DO_FCALL                                      0  $1      
          3        CONCAT                                           ~2      'Client%3A+I%27m+not+aware+of+the+creator%27s+class%2C+but+it+still+works.%0A', $1
          4        ECHO                                                     ~2
  108     5      > RETURN                                                   null

End of function refactoringguru%5Cfactorymethod%5Cconceptual%5Cclientcode

Class RefactoringGuru\FactoryMethod\Conceptual\Creator:
Function factorymethod:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  factoryMethod
number of ops:  2
compiled vars:  none
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   23     0  E >   VERIFY_RETURN_TYPE                                       
          1      > RETURN                                                   null

End of function factorymethod

Function someoperation:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  someOperation
number of ops:  11
compiled vars:  !0 = $product, !1 = $result
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   35     0  E >   INIT_METHOD_CALL                                         'factoryMethod'
          1        DO_FCALL                                      0  $2      
          2        ASSIGN                                                   !0, $2
   37     3        INIT_METHOD_CALL                                         !0, 'operation'
          4        DO_FCALL                                      0  $4      
          5        CONCAT                                           ~5      'Creator%3A+creator%27s+code+has+just+worked+with+', $4
          6        ASSIGN                                                   !1, ~5
   39     7        VERIFY_RETURN_TYPE                                       !1
          8      > RETURN                                                   !1
   40     9*       VERIFY_RETURN_TYPE                                       
         10*     > RETURN                                                   null

End of function someoperation

End of class RefactoringGuru\FactoryMethod\Conceptual\Creator.

Class RefactoringGuru\FactoryMethod\Conceptual\ConcreteCreator1:
Function factorymethod:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  factoryMethod
number of ops:  6
compiled vars:  none
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   57     0  E >   NEW                                              $0      'RefactoringGuru%5CFactoryMethod%5CConceptual%5CConcreteProduct1'
          1        DO_FCALL                                      0          
          2        VERIFY_RETURN_TYPE                                       $0
          3      > RETURN                                                   $0
   58     4*       VERIFY_RETURN_TYPE                                       
          5*     > RETURN                                                   null

End of function factorymethod

Function someoperation:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  someOperation
number of ops:  11
compiled vars:  !0 = $product, !1 = $result
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   35     0  E >   INIT_METHOD_CALL                                         'factoryMethod'
          1        DO_FCALL                                      0  $2      
          2        ASSIGN                                                   !0, $2
   37     3        INIT_METHOD_CALL                                         !0, 'operation'
          4        DO_FCALL                                      0  $4      
          5        CONCAT                                           ~5      'Creator%3A+creator%27s+code+has+just+worked+with+', $4
          6        ASSIGN                                                   !1, ~5
   39     7        VERIFY_RETURN_TYPE                                       !1
          8      > RETURN                                                   !1
   40     9*       VERIFY_RETURN_TYPE                                       
         10*     > RETURN                                                   null

End of function someoperation

End of class RefactoringGuru\FactoryMethod\Conceptual\ConcreteCreator1.

Class RefactoringGuru\FactoryMethod\Conceptual\ConcreteCreator2:
Function factorymethod:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  factoryMethod
number of ops:  6
compiled vars:  none
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   65     0  E >   NEW                                              $0      'RefactoringGuru%5CFactoryMethod%5CConceptual%5CConcreteProduct2'
          1        DO_FCALL                                      0          
          2        VERIFY_RETURN_TYPE                                       $0
          3      > RETURN                                                   $0
   66     4*       VERIFY_RETURN_TYPE                                       
          5*     > RETURN                                                   null

End of function factorymethod

Function someoperation:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  someOperation
number of ops:  11
compiled vars:  !0 = $product, !1 = $result
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   35     0  E >   INIT_METHOD_CALL                                         'factoryMethod'
          1        DO_FCALL                                      0  $2      
          2        ASSIGN                                                   !0, $2
   37     3        INIT_METHOD_CALL                                         !0, 'operation'
          4        DO_FCALL                                      0  $4      
          5        CONCAT                                           ~5      'Creator%3A+creator%27s+code+has+just+worked+with+', $4
          6        ASSIGN                                                   !1, ~5
   39     7        VERIFY_RETURN_TYPE                                       !1
          8      > RETURN                                                   !1
   40     9*       VERIFY_RETURN_TYPE                                       
         10*     > RETURN                                                   null

End of function someoperation

End of class RefactoringGuru\FactoryMethod\Conceptual\ConcreteCreator2.

Class RefactoringGuru\FactoryMethod\Conceptual\Product:
Function operation:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  operation
number of ops:  2
compiled vars:  none
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   75     0  E >   VERIFY_RETURN_TYPE                                       
          1      > RETURN                                                   null

End of function operation

End of class RefactoringGuru\FactoryMethod\Conceptual\Product.

Class RefactoringGuru\FactoryMethod\Conceptual\ConcreteProduct1:
Function operation:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  operation
number of ops:  3
compiled vars:  none
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   85     0  E > > RETURN                                                   '%7BResult+of+the+ConcreteProduct1%7D'
   86     1*       VERIFY_RETURN_TYPE                                       
          2*     > RETURN                                                   null

End of function operation

End of class RefactoringGuru\FactoryMethod\Conceptual\ConcreteProduct1.

Class RefactoringGuru\FactoryMethod\Conceptual\ConcreteProduct2:
Function operation:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/YRu5A
function name:  operation
number of ops:  3
compiled vars:  none
line      #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   93     0  E > > RETURN                                                   '%7BResult+of+the+ConcreteProduct2%7D'
   94     1*       VERIFY_RETURN_TYPE                                       
          2*     > RETURN                                                   null

End of function operation

End of class RefactoringGuru\FactoryMethod\Conceptual\ConcreteProduct2.

Generated using Vulcan Logic Dumper, using php 8.0.0


preferences:
171.91 ms | 1411 KiB | 15 Q