开发者

Constants in Kohana

开发者 https://www.devze.com 2023-02-08 09:47 出处:网络
I\'ve used codeigniter in the past but on my current project I\'m making the switch to Kohana.What is the best practice on constants?

I've used codeigniter in the past but on my current project I'm making the switch to Kohana. What is the best practice on constants?

In codeigniter there is the actual constan开发者_如何学编程ts.php, but going through Kohana's source I'm not seeing something similar.


Never used kohana, but after a quick googling I find that you can use the config API to create your own config that will house the constants you need.

This thread suggests that if you are storing database sensitive items, to place them in the database.php config, etc.. making them relative to the type of data they are storing.


I'm familiar with Kohana, but not CI so much, so I'm guessing a bit to what you mean by 'constants.' I believe the closest thing to this is indeed Kohana's config API. So, if you wanted to make templates aware of some site-wide constant like your site name, that's a great thing to use the config API for.

To accomplish this, you'll need to create a config file under your /config folder, probably in the /application directory. What you call it isn't very important, but since it contains site information, let's call it site.php.

To quickly get going, here is what you'll want to have in that file:

<?php defined('SYSPATH') or die('No direct script access.');

return array(
    // Your site name!
    'name' => 'Oh me, Oh my',
);

Now, you can bring this in to a template by doing something like:

A better way to do this (using dumb templating) would be to assign this as a template variable in your Controller. So, assuming you have some default controller set up, the code would be:

public function action_index() {

    $this->template->site_name = Kohana::config('site.name');

}

And then your template would have something like this:

<title><?php echo $site_name; ?></title>

Kohana's config API is interesting because it is hierarchical, meaning you can override and merge new configuration values on top of existing config structures. When you call Kohana::config('site.name'), the engine looks through all the config files named site.php, runs all of those config files and merges the results in to an array. The application-level config files will overwrite modules, which will overwrite system, etc... Then, based on that result array, Kohana will attempt to find the 'name' key and return it.


Assuming you want global constants...the following worked well for me.

application/config/constants.php:

define('MY_COOL_CONSTANT', 'foo');
return array();

index.php:

Kohana::$config->load('constants');

MY_COOL_CONSTANT should then be available globally.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号