简体   繁体   English

在Codeigniter 2中,如何将库加载到可以在辅助函数中使用的全局变量中?

[英]In Codeigniter 2, how do I load a library into a global variable I can use in helper functions?

So I have the following files: 所以我有以下文件:

libraries/foo_library.php 库/ foo_library.php

helpers/foo_helper.php 助手/ foo_helper.php

views/main.php 意见/ main.php

Now my problem: The library I've created is going to be used hundreds of times on each page load since it's used for determining the language and returning the correct item depending on the language stored in the database. 现在我的问题是:我创建的库将在每次页面加载时使用数百次,因为它用于确定语言并根据数据库中存储的语言返回正确的项目。

<?=$this->foo_library->language('English');?>

Now when used that way it works fine, though since I'm going to be using it for other language operations in the views, I created a few helper functions to make the views look cleaner 现在,以这种方式使用它可以正常工作,但是由于我将在视图中将其用于其他语言操作,因此我创建了一些帮助器函数以使视图看起来更整洁

<?=sl('English words','Other language words')?>

Now this does work to an extent, though the helper ends up creating a new object from the library every time the function is run (Basically using the $CI =& get_instance() method to call the library). 现在这确实可以工作,尽管每次函数运行时助手最终都会从库中创建一个新对象 (基本上使用$ CI =&get_instance()方法来调用该库)。

This is a problem, since when you create the library, it saves data into memory so it doesn't need to keep querying the database. 这是一个问题,因为在创建库时,它会将数据保存到内存中,因此不需要继续查询数据库。 So when the object gets recreated over and over again, it completely defeats the purpose . 因此, 当一遍又一遍地创建对象时,它完全无法达到目的

So I wanted to know, is there any clean way for my to create a library object that can be used anywhere in the project, including helper functions, and maintain it's persistence? 因此,我想知道,有没有一种干净的方法可以创建可在项目中的任何地方使用的库对象(包括辅助函数)并保持其持久性? ( The library does use the db builder class from CI ) 该库确实使用了CI的db builder类

You can autoload some elements on Codeigniter so you can access them globally 您可以在Codeigniter上自动加载某些元素,以便可以全局访问它们

The following items can be loaded automatically: 可以自动加载以下项目:

Classes found in the libraries/ directory Helper files found in the helpers/ directory Custom config files found in the config/ directory Language files found in the system/language/ directory Models found in the models/ folder 在librarys /目录中找到的类helpers /目录中找到的帮助程序文件config /目录中找到的自定义配置文件system / language /目录中找到的语言文件models /文件夹中找到的模型

Autoloader 自动加载磁带机

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM