jmasci/component-template

此包的最新版本(dev-master)没有提供许可证信息。

创建灵活的HTML渲染模板的基础类,这些模板由可覆盖的可调用组件组成。

dev-master 2020-01-27 20:03 UTC

This package is auto-updated.

Last update: 2024-09-28 06:53:43 UTC


README

组件

组件是一个对象,它封装了一个可调用对象和一个由可调用对象组成的参数过滤器数组。它有一个invoke方法,该方法将过滤参数然后调用可调用对象。

在模板的上下文中,组件的作用更加清晰,它们在模板实例化之后可以覆盖,类似于类方法,但我们可以覆盖它们。

请注意,添加参数过滤器获得的某些行为有时可以通过覆盖可调用对象或在其他可调用对象内部调用可调用对象来获得。

use JMasci\ComponentTemplate\Component;

$comp = new Component( function( $a_number ){
    echo "You passed in: " . (int) $a_number;    
});

// filters are callbacks that accept the same arguments as the callable and returns
// the arguments in a list.
// this is an example of a completely redundant filter.
$comp->set_filter( function( $a_number ){
    return [ $a_number ];
});

// a filter which does not like the number 42
$comp->set_filter( function( $a_number ){
    return [ $a_number === 42 ? 11 : $a_number ];
});

// a filter which doubles
$comp->set_filter( function( $a_number ){
    return[ $a_number * 2 ];
});

// prints 22
// the first parameter of invoke is called $new_this. You can use it to bind an object
// to $this inside of the callable.
echo $comp->invoke( null, 42 );

模板

模板是一个对象,它简单地封装了一组组件。当你调用一个组件时,它默认将自身作为 $new_this 传递。这使得组件在同一模板内部调用其他组件变得最容易。这使得组件更像模板的动态(可覆盖)方法。

use JMasci\ComponentTemplate\Template;

// specify the name of the top level component to invoke upon $template->render().
// we can also specify a callback here if needed (as 2nd parameter).
$template = new Template( 'main', $render_callback = null );

// set the main component. Pass in a function but it will store a Component object.
// once again, $this inside the callback will refer to the template by default, but you
// could change this behaviour by extending Template and re defining the invoke method. 
$template->set( 'main', function( $p1, $p2 ){
    ?>
    <div class="example-template">
        <p><?php $this->invoke( 'comp_2', $p1, $p2, 50 ); ?></p>            
    </div> 
    <?php    
});

$template->set( 'comp_2', function( $p1, $p2, $p3 ){    
    echo intval( $p1 + $p2 + $p3 );    
});

// you can override comp_2 at any time.
$template->set( 'comp_2', function( $p1, $p2, $p3 ){    
    echo intval( $p1 + $p2 - $p3 );    
});

$template->get( 'comp_2' )->set_filter( function( $p1, $p2, $p3 ) {
    return [ $p1, 2 * $p2, $p3 ];
});

echo $template->render( 10, 30 );

你可以使用高阶函数和模板工厂的组合做更多的事情,但这只是展示了基本示例。