-
Notifications
You must be signed in to change notification settings - Fork 120
Extending the class
Jorge Castro edited this page Apr 22, 2020
·
1 revision
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();
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';
}
}
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")
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")
Copyright Jorge Castro Castillo
- BladeOne Manual
- Template tags (views)
- Custom control
- Methods of the class
- Injecting logic before the view (composer)
- Extending the class
- Using BladeOne with YAF Yet Another Framework
- Differences between Blade and BladeOne
- Comparision with Twig (May-2020)
- Changelog
- Changes between 2.x and 3.0 and TODO
- Code Protection (Sourceguardian and similars)