PHP code example of decodelabs / archetype

1. Go to this page and download the library: Download decodelabs/archetype library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

decodelabs / archetype example snippets



// Main library
namespace My\Library
{

    use DecodeLabs\Archetype;

    interface Thing {}

    class Factory {

        public static function loadThing(string $name): Thing
        {
            // Resolve name to class for Thing interface
            $class = Archetype::resolve(Thing::class, $name);

            return new $class();
        }
    }
}


// Thing implementations
namespace My\Library\Thing
{

    use My\Library\Thing;

    class Box implements Thing {}
    class Potato implements Thing {}
    class Dog implements Thing {}
}



// Calling code
namespace My\App
{

    use My\Library\Factory;

    $box = Factory::loadthing('Box');
    $potato = Factory::loadThing('Potato');
    $dog = Factory::loadThing('Dog');
}

namespace My\Library {

    use DecodeLabs\Archetype\Resolver;

    class ThingArchetype implements Resolver
    {

        public function getInterface(): string
        {
            return Thing::class;
        }

        public function getPriority(): int
        {
            return 10;
        }

        public function resolve(string $name): ?string
        {
            return 'Some\\Other\\Namespace\\'.$name;
        }
    }
}

use DecodeLabs\Archetype;
use My\Library\Resolver\Alternative as AlternativeResolver;

Archetype::register(new AlternativeResolver());

use DecodeLabs\Archetype;

foreach(Archetype::scanClasses(Thing::class) as $path => $class) {
    echo 'Found class: '.$class.' at '.$path.PHP_EOL;
}

namespace My\Library {

    use DecodeLabs\Archetype\Finder;

    class ThingArchetype implements Finder
    {

        public function getInterface(): string
        {
            return Thing::class;
        }

        public function getPriority(): int
        {
            return 10;
        }

        public function resolve(string $name): ?string
        {
            return 'Some\\Other\\Namespace\\'.$name;
        }

        public function findFile(string $name): ?string
        {
            return './some/other/namespace/'.$name.'.jpg';
        }
    }
}


namespace My\App {

    use DecodeLabs\Archetype;
    use My\Library\Thing;

    $boxImagePath = Archetype::findFile(Thing::class, 'box');
}