Question

I use smarty modifier a lot, sometimes some function need to connect to database, but it seems cannot extend parent php connect setting, I need to to MySQL connect itself,

PHP

// connect function
$smarty->assign('datas', $datas');
$smarty->display('template.tpl');

template

{if $datas}
{foreach $datas as $data}
echo {$data|my_function}
{/foreach}
{/if}

modifier function

function smarty_modifier_my_function($src) {
    // connect function
    // do something
}

Is that mean if I have 10 data this page request database connection 11 times? How to do the same thing just request one database connection.

Was it helpful?

Solution

I agree with Foobar when he said that your 'views' aren't supposed to contain DB connection, so I suggest you another solution to deal with your problem :

Create an object that maps your data with a property that contains your button specifications. This can be done as follow :

PHP

// Define a class that maps your data 
class myClass
{
    public $id;
    public $a; // your data keys here
    public $b; // your data keys here
    public $some_button;

    public function __construct($data)
    {
        $this->id = $data['id'];
        $this->a  = $data['a'];
        $this->b  = $data['b'];

        $this->set_some_button($data['id']);
    }

    protected function set_some_button($id) {

        if ($id == 1) 
            $this->some_button = 'button1';
        elseif ($id == 2) 
            $this->some_button = 'button2';
        else 
            $this->some_button = 'button0';
    }
}

// Create an array of objects that maps your datas 
$objects = array();
foreach ($datas as $data) {
    $objects[] = new myClass($data);
}

// Pass this array to the view
$smarty->assign('objects', $objects);
$smarty->display('template.tpl');

Template

// access your data as follow
{foreach $objects as $obj}
    {$obj->id}
    {$obj->a}
    {$obj->b}
    {$obj->some_button}
{/foreach}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top