Skip to content

Extending the class

Jorge Castro edited this page Apr 22, 2020 · 1 revision

Extending the class

There are several ways to add more tags and extending the class with new functionalities.

The official way to extend the class is creating a new PHP trait as follow:

trait TraitExample
{
	// our code
}

And we need to define the next class

class ClassUsingTraitExample extends BladeOne
{
    use TraitExample;
}
$blade=new ClassUsingTraitExample(); // instead of $blade=new BladeOne();

Adding a constructor to the trait

To add a constructor to each trait, we must create a new public function without arguments and with the name of the trait.

trait TraitExample
{
    public $fieldTrait; // example field
    /**
     * Constructor. It must has the name of the trait, it must be public and it must has zero arguments.
     */
    public function TraitExample()
    {
        $this->fieldTrait='loaded';
    }
}

Adding a new tag (classic)

It is an example of a new method. The method must be public and called "compile"+ name of the new tag

You can see an example in tests/OtherTest.php

trait TraitExample
{
    /**
     * We create the new tags @hello <br>
     * The name of the method must starts with "compile"<br>
     * <b>Example:</b><br>
     * <pre>
     * @hello()
     * @hello("name")
     * </pre>
     *
     * @param null|string $expression expects a value like null, (), ("hello") or ($somevar)
     * @return string returns a fragment of code (php and html)
     */
    public function compileHello($expression=null)
    {
        if ($expression===null || $expression==='()') {
            return "<?php echo '--empty--'; ?>";
        }
        return "<?php echo 'Hello '.$expression; ?>";
    }
}

The tag could be called in the view as follow

@hello()
@hello("name")

Adding a new tag (named argument)

trait TraitExample
{
    /**
     * We create the new tags @ hellonamed <br>
     * The name of the method must starts with "compile"<br>
     * <b>Example:</b><br>
     * <pre>
     * @hellonamed()
     * @hellonamed(name="name")
     * </pre>
     *
     * @param null|string $expression expects a value like null, (), ("hello") or ($somevar)
     * @return string returns a fragment of code (php and html)
     */
    public function compileHelloNamed($expression)
    {
        $args = $this->getArgs($expression); // args separates the arguments by name
        $name=isset($args['name']) ? $args['name'] : '--empty--';
        return "<?php echo 'Hello '.$name; ?>";
    }

}

The tag could be called in the view as follow

@hellonamed()
@hellonamed(name="name")