Search code examples
variablescakephpincludevendor

Cakephp use Variables from Vendor php file


I've imported a selfwritten PHP Vendor file in Cakephp 2.X like this

View: XXX.ctp:

App::import('Vendor', 'languages', array('file' => 'variables/toUse.php'));

In this file I've declared some variables like this, in order to use them in the view:

toUse.php:

$test = 'Placeholder';
$anotherTest = 'anotherPlaceholder';

but unfortunately I can't use the variable in my view:

Notice (8): Undefined variable: test [APP/View/XXX/XXX.ctp, line X]

But for example a Debugger::dump() inside my toUse.php is displayed correctly in my view XXX.ctp..

So my Question is, is it not possible to use variables from the imported vendor files, or do I've made something wrong?


Solution

  • It would be better to set your variables in the Controller. If these need to be accessible by multiple controllers (as suggested in your comment) then you can do this in the beforeRender() callback of AppController:-

    public function beforeRender() {
        $this->set('test', 'Placeholder');
        $this->set('anotherTest', 'anotherPlaceholder');
    }
    

    You can then use these as normal in your View templates:-

    echo $test;
    

    Vendor files shouldn't really be used for setting data for a View.