简体   繁体   中英

How do I structure my Controllers in CodeIgniter given the conditions

I am trying to build a web API with CodeIgniter as PHP framework.

This is not a REST api. It is just a Web api which mean all queries will be POST queries.

A typical query will look like this

http://host/api1/user/get_name

and

http://host/api2/user/get_name

Under such circumstances api1 and api2 become controllers and user becomes a method under it.

I am not happy with this because then my api1 and api2 classes become too large and also I dont like to mix unrelated code in a single class.

What can I do ? Can I play with my .htaccess file or the routing configuration such that everytime the server receives a request of the form \\^api\\ it forwards it to appropriate controller ?

Please note that api1 and api2 are not the only controllers in my system.

You have to consider the couple of things

  1. Are they interdependent?
  2. You must have some specific reason for maintaining 2 web APIs.

If they are not interdependent then i will recommend you to do this

http://host1/user/get_name
http://host2/user/get_name

If they are interdependent then you must do

http://host/api1/user/get_name
http://host/api2/user/get_name

Reason behind that is you do not need to maintain the 2 different models.

For example, if you made some changes in a X_model.php , you have to upload that on both server.

And you can create folder under controller. I am very confirm about that. I have done it in codeigniter 1.7 .

So you can create folder respectively and continue with it.!

You could try $route['api(:num)'] = "api$1/";

Haven't tested dunno if it's gonna work the way you want it.

Codeigniter Routing

What are API1 and API2? Are they independent of each other?

If so, I would recommend you use separate subdomains for the two APIs, so you can do this:

http://api1.example.com/user/get_name
http://api2.example.com/user/get_name

This provides a clear separation between the two APIs, and allows User to be the controller as opposed to the entire API.

This would require you to create two directories ( api1, api2 ) in your hosting root, 'install' two instances of CI and route the subdomains to the respective directories.

i see nothing wrong with your url scheme. this is how you are supposed to call controller -> action in codeigniter. If you want your controllers to be skinny move the actual processing code in libraries and call the libraries for each request. Or you could play with the rewrite rules to distribute the work across different controllers.

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