简体   繁体   中英

CodeIgniter: Best way to implement External Objects (Objects that aren't models, views, or controllers)?

I want to add some classes to a CodeIgniter project that aren't models, views, or controllers. They will most likely be a built in Models/Controllers and used in various ways. Where should I store these classes, and what is the best way to implement them in CodeIgniter? (Or more generally, any MVC-based framework?).

EDIT: Looking through some of the codeIgniter documentation, it looks like adding the objects to a helper is the way to go, is that correct?

CI is unlike a lot of MVC frameworks in that it doesn't make it challenging to integrate outside libraries. Generally, there are a couple approaches:

  1. Just include()/require() the library and use it normally. This works fine most of the time, unless there's a naming conflict. CI mostly stays out of the way, so this isn't common. In this case, you can put the library wherever you feel like. Generally I try to keep them in a shared "libs" directory, outside of the document root, since I don't assume they'll only be used by CI.

  2. Put your libraries in your applications/libraries and load them using the CI->load() method. This puts some restrictions on naming conventions, so you might need to massage existing libraries or write some sort of wrapper constructor. The CI docs on creating libraries covers this pretty well.

Personally, I much prefer the first approach. It's one of the benefits of using CI.

Personally, if there is no possibility of it being a library, I will either put it in the helpers folder as objects_helper.php or, in special circumstances, in the same file as the Library object which calls it.

You might also look into a object factory library so you could use something like:

$this->factory->createUserObject( $name, $rank, $serial );

Finally, you could look into the hooks framework, but it does not sound like you really want to use that.


I would only use require/include if you feel that it does not make sense (from a code/philosophical perspective) in any other circumstance. It is generally a good idea to work within a framework whenever possible.

I would recommend making it a library and just using $this->load->library(); To read mores see: http://codeigniter.com/user_guide/general/creating_libraries.html

There is a difference between libraries and helpers. If the outside library isn't object-oriented then you'll want it as a helper, if it is, then you should just be able to make it a library with no problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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