Fork me on GitHub

Injection de dépendance


Cet exemple montre comment injecter des dépendances dans le constructeur des classes Jaxon.

 

The ExampleInterface is defined in the Jaxon service container, and injected in the HelloWorld component.

The HTML code.

<div class="row">
    <div class="col-md-12" id="hello-text-two">
        &nbsp;
    </div>
    <div class="col-md-4 select">
        <select class="form-select form-control" id="colorselect" name="colorselect" <?= attr()
            ->on('change', rq('HelloWorld')->setColor(Jaxon\select('colorselect'))) ?>>
            <option value="black" selected="selected">Black</option>
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
        </select>
    </div>
    <div class="col-md-8 buttons">
        <button type="button" class="btn btn-primary" <?= attr()
            ->click(rq('HelloWorld')->sayHello(1, 'Thierry Feuzeu')) ?>>CLICK ME</button>
        <button type="button" class="btn btn-primary" <?= attr()
            ->click(rq('HelloWorld')->sayHello(0, 'Thierry Feuzeu')) ?>>Click Me</button>
    </div>
</div>

The injected interface and service

The Jaxon library config

The Jaxon setup code.

<?php

use Jaxon\Jaxon;
use Jaxon\App\FuncComponent;
use Service\ExampleInterface;

// Register the namespace with a third-party autoloader
$loader = new Keradus\Psr4Autoloader;
$loader->register();
$loader->addNamespace('Service', ajaxDir('/namespace/service'));

class HelloWorld extends FuncComponent
{
    protected $service;

    public function __construct(ExampleInterface $service)
    {
        $this->service = $service;
    }

    public function sayHello(bool $isCaps, $sMessage)
    {
        $sMessage = $this->service->message($isCaps) . ', ' . $sMessage;
        $this->response()->assign('hello-text-two', 'innerHTML', $sMessage);
    }

    public function setColor(string $sColor)
    {
        $sColor = $this->service->color($sColor);
        $this->response()->assign('hello-text-two', 'style.color', $sColor);
    }
}

// Register object
$jaxon = jaxon();

$jaxon->app()->setup(configFile('container.php'));
$jaxon->setOption('core.decode_utf8', true);

$jaxon->register(Jaxon::CALLABLE_CLASS, HelloWorld::class);
The Javascript code is generated from this PHP template.

jaxon.dom.ready(() => {
    // Call the HelloWorld class to populate the 2nd div
    <?= rq('HelloWorld')->sayHello(0, 'Thierry Feuzeu') ?>;
    // call the HelloWorld->setColor() method on load
    <?= rq('HelloWorld')->setColor(Jaxon\select('colorselect')) ?>;
});