CodeIgniter全局函数 [英] CodeIgniter global function
问题描述
我在哪里可以放置我的全局函数,如果用户登录,它会检查?
Where can I place my "global" function, which will check, if user is logged in?
因为我想做一些类似的事情:只有当函数 isLogged()
返回TRUE,并且我必须在一些视图中使用它时才浏览一些页面,这就是为什么它应该是一个全局函数我可以从任何地方访问。
Because I want to do something like: user is able to browse some pages only when the function isLogged()
returns TRUE, and I'd have to use it in some views, that's why it should be a "global" function, which I can access from anywhere.
这是可能吗?或者有更好的解决方案吗?
Is that possible? Or there is any better solution for this?
推荐答案
你应该把它放入一个库,并自动加载库。当您需要在视图中使用logged_in标志时,从控制器传递它。示例:
You should probably put it into a Library, and autoload the library. When you need to use the "logged_in" flag in a view, pass it in from the controller. Example:
application / libraries / Auth.php
p>
application/libraries/Auth.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Auth
{
public function is_logged_in ()
{
// Change this to your actual "am I logged in?" logic
return $_SESSION['logged_in'];
}
}
$ b b
application / config / autoload.php
...
$autoload['libraries'] = array(
...
'auth',
...
}
`application / controllers / welcome.php
`application/controllers/welcome.php
<?php ...
public function index ()
{
$view_data = array
(
'logged_in' => $this->Auth->logged_in()
);
$this->load->view('my_view', $view_data);
}
application / views / my_view.php
<? echo $logged_in ? 'Welcome back!' : 'Go login!' ?>
这篇关于CodeIgniter全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!