phparchitect-2019-08

(Rick Simeone) #1
38 \ August 2019 \ http://www.phparch.com

Generated Singletons


Internal Apparatus


No Return Type
Listing 2, class CarleyStatePark, is identical to Listing 1
except that getInstance() does not specify a return type.
Does the generated code change? Yes, it does. The getIn-
stance() return sequence is shorter. We don’t see the
VERIFY_RETURN_TYPE V6 instruction. Now we know how, or at
least where, the PHP virtual machine implements the func-
tion/method return type. The VERIFY_RETURN_TYPE instruction
handles that task.
Here is the fragment of generated code for CarleyStatePark.
It returns self::$instance as before, but does not check the
return type:

L12 (17): EXT_STMT
L13 (17): V6 = FETCH_STATIC_PROP_R string("instance") (self)
(exception)
L14 (17): RETURN V6

Remove Duplication
We now have two nearly-identical classes, CamdenState-
Park and CarleyStatePark. Let’s remove code duplication by
creating a parent class. CamdenStatePark and CarleyStatePark
will extend that parent class. This is a mistake, but we don’t
know that yet, so let’s keep going! See Listing 3.
Here are the modified child classes, Listing 4 and Listing 5.
We added require_once 'StatePark.php'; so the code gener-
ator can find the parent class. Note that we add the @method
annotation to each child class, so our editor can help us keep
the object types correct (see line 8 of Listing 4 and Listing 5).


Listing 3. Class StatePark


  1. <?php

  2. declare(strict_types=1);



  3. namespace App\GeneratedSingleton;



  4. abstract class StatePark {

  5. /* @var StatePark /

  6. private static $instance;



  7. private function __construct() {

  8. }



  9. public static function getInstance(): self {

  10. if (!self::$instance) {

  11. self::$instance = new static;

  12. }

  13. return self::$instance;

  14. }



  15. }


Listing 4. Modified class CamdenStatePark


  1. <?php

  2. declare(strict_types=1);



  3. namespace App\GeneratedSingleton;

  4. require_once 'StatePark.php';



  5. /**



    • @method static getInstance() : CamdenStatePark



  6. */

  7. class CamdenStatePark extends StatePark {

  8. }


Listing 5. Modified class CarleyStatePark


  1. <?php

  2. declare(strict_types=1);



  3. namespace App\GeneratedSingleton;

  4. require_once 'StatePark.php';



  5. /**



    • @method static getInstance() : CarleyStatePark



  6. */

  7. class CarleyStatePark extends StatePark {

  8. }


Listing 2. Class CarleyStatePark


  1. <?php

  2. declare(strict_types=1);



  3. namespace App\GeneratedSingleton;



  4. class CarleyStatePark {

  5. /* @var CarleyStatePark /

  6. private static $instance;



  7. private function __construct() {

  8. }



  9. public static function getInstance() {

  10. if (!self::$instance) {

  11. self::$instance = new self;

  12. }

  13. return self::$instance;

  14. }

  15. }

Free download pdf