codeigniter class name convention - codeigniter-2

When I'm developing in NetBeans I have a lot of confusion due to the amount of tabs open. In most cases the controller has the same name of the view or model.
In the convention style guide they say that you can prefix a controller file name with a custom suffix, but doesn't work.
My question is, there is any chance to end all the controller files with "_controller"?
In my example the class is class Verify_login extends CI_Controller { and the file is named verify_login.php. Tried with controller.verify_login.php like they say in the guideline but as I say, doesn't work. Lots of confusion in codeigniter's documentation.

Since the controller is the only thing exposed in the URL, I usually name my views and models with an indicator like "user_view" or "user_model". The controller would just be "user" and in this way I always know which file I'm working on.

Related

Separate Laravel controller for each URL route?

I am building a REST API server (in Lumen, actually, rather than Laravel) with multiple endpoints that allow various operations to be performed on resources such as Users, Accounts, and Products. For example, here are the routes I have defined for the User resource:
GET /v1.0/user
POST /v1.0/user
GET /v1.0/user/{username}
PUT /v1.0/user/{username}
DELETE /v1.0/user/{username}
I currently have all of these API routes for a particular resource defined in a single controller. For example, here are my routes for the User resource:
$router->get('/v1.0/user', 'UserController#listAll');
$router->post('/v1.0/user', 'UserController#createUser');
$router->get('/v1.0/user/{username}', 'UserController#getUser');
$router->put('/v1.0/user/{username}', 'UserController#updateUser');
$router->delete('/v1.0/user/{username}', 'UserController#deleteUser');
Some of the controller logic is getting pretty complex, and I am now finding that my controller files are getting really, really long. I am now thinking that I should use a separate controller file for each route, to make the code more maintainable.
My question is whether there is any idiom or convention I should follow with regard to file/folder naming or structure. Should I create a subfolder under Controllers for each resource (ex: Controllers/User/UserCreateController.php)? Or is this entirely a matter of personal choice?
You should check out Single Action Controller which take only the __invoke() method and can handle one single route.
By the way, what I see usually is that when a controller logic is getting complex, is time to refactor and move that complexity outside the controller.
You do not need to create sub folders or multiple controllers. Use a single controller User Controller which only contains entry points of each route. Move the business logic outside of the controller by creating a class or group of classes that take care of the process.
For example : You can create another directory Libraries under app folder and create a class User under Libraries which contains all functions of User resource.
app/Libraries/User.php
namespace App\Libraries;
class User {}
Now, you can access this class and functions using the namespace within your User Controller
namespace App\Http\Controllers;
use App\Libraries\User;
class UserController extends Controller {}

Should all models be represented in DB, or better to make only a controller if modell is not represented in DB?

I wonder about the route leading to the welcome-page in my project. You reach it with the '/'-route .
Where should the method handling this route be and what is the correct structure behind it?
I get two ideas spontaneously:
Make a model named something like Home and put the method in HomeController
(Con: I thought all modells should be represented in DB?)
...
Make only a controller named HomeController, no model
(Con: Feels wrong to have a controller for a modell that does not exist?)
What is correct?
I can't comment so I'll leave it here.
Both Model and Controller are just Class. If you take a look at your HomeController and your User.php model you'll see they extend Controller and Model Classes, respectively.
As many said there is no need to have 1 to 1 relationship between Controllers and Models.
Invest some time to learn basics of OOP and you will see that you can have as much classes as you want, and there are many ways to relate them. Some of the Classes are Controllers, some are Models and some are something completely else, like Exceptions. But at all times keep in mind that, in the end, they are just Classes implementing some interface, using some traits, and extending other Classes.
It's worth to do this at the start of your learning process. It will steepen your learning curve a bit but in the long run it's well worth it.
You don't need a model for each controller or vice versa, just add them as needed according to your application: need CRUD actions or other interaction with your model. Try creating a WecolmeController as the HomeController is the default one for after login features (or change it accordingly if needed).

Correct naming structure for CodeIgniter

I'm starting my 1st CodeIgniter project and want to get some advice before i start. I'm a little confused with how the name of the controller and models work.
If i want the url to my company page to be http://example.com/Company/view
the controller needs to be called Company.php correct?
inside the company controller it would look like this:
public function viewAll()
{
$this->load->model('Companymodel');
$this->load->view('templates/header');
$data['result'] = $this->Companymodel->viewAll();
$this->load->view('company/viewAll', $data);
$this->load->view('templates/footer');
}
ok im confused here, on line 4 above:
$this->load->model('Companymodel');
this call to the company model page needs to have 1st letter capital with the rest lower case?
if that's correct, does the model file need to be called Companymodel.php and placed inside the application/models folder?
is it bad practice to call the controller and model the same
example: Company.php and place it inside /application/controller/
and then have the model called Company.php and place it inside the application/model or should the model be called Companymodel.php
I guess my ultimate question is the naming convention of the controller and model files, and whether they can be upper case or not.
URLs
Your URLs should typically be all lowercase letters. If you expect capital letters, there's a chance you could accidentally exclude their lowercase counterparts, even though they're the same URL. Example: www.example.com/controller/method/param
Controllers
Controller class names should be all lowercase, except the first letter.
If your URL is www.example.com/gallery, the controller name is Gallery.
If your URL is www.example.com/admin_folder, the controller name is Admin_folder.
Controller file names should match the class name, but be all lowercase.
Gallery :: gallery.php
Admin_folder :: admin_folder.php
Controller methods should be all lowercase as well. There is some flexibility with uppercase, but similar to URLs, there are opportunities where it can goof something up (here's an example where capital letters interfered with a form validation callback method).
Models
Models follow most of the same conventions as controllers. The only difference is with model method names, which can use your preference of capitalization. Since these methods are not tied to URLs, and are called using normal PHP OOP, you can name them as you please.
It is recommended to load models using the all lowercase version. While it is not required by CI, it can confuse some users if they load it with a capital letter, but then attempt to access it as all lowercase (this is due to native PHP being case sensitive with class properties [and variables in general], not CodeIgniter).
Model class name: Users_model (the _model suffix is also not required, but some people may use it as a personal preference, or to prevent naming conflicts with a Users controller).
Model file name: users_model.php
Model loading: $this->load->model('users_model')
Model method names (all okay): $this->users->getAll(), $this->users->find_by_name($name), etc.
Libraries
Libraries follow the same conventions except for the file name. In their case, file names should match the class name.
Similar to models, it's recommended to load libraries using the lowercase name.
These rules are the same for CI's libraries (located in application/core and application/libraries, as well as custom or third-party libraries.
Special note: when extending default CI libraries, the prefix as defined in application/config.php comes into play. This prefix typically should be all uppercase, followed by an underscore. The default is MY_.
Library class name: Photos
Library file name: Photos.php,
Library load: $this->load->library('photos')
Helpers
Helper names and loading are all lowercase. The filename consists of the helper name with _helper appended after.
Helper name: url
Helper file name: url_helper.php
Helper load: $this->load->helper('url')
Notes
CodeIgniter is somewhat inconsistent in their naming conventions, but there really aren't too many rules, so they are easy to get used to and memorize. I very rarely have issues with naming and loading in CI, and when I do, it's usually because I was just working on a Composer-related project so I got into a different habit.
The rules in this answer are for CodeIgniter 2.1.x as of this writing. There is discussion on Github for 3.0 to better and add more consistency to naming conventions, which you can read about and contribute to if you'd like.
models/admin.php
<?php
class Admin extends CI_Model {
...etc
controllers/company.php
will include the admin model with
function galleryView()
{
$this->load->model('Admin');
$numRows = $this->Admin->getPhotoNum();
... etc
To browse to galleryView the URL would be mysite.com/company/galleryView
There is very good documentation and examples on the CodeIgniter site

how load model in another modules in hmvc in codeigniter?

I want to use The Modular Extensions HMVC in my Project like this:
modules
module01
models
models01.php
controllers
controller01.php
views
views01.php
module02
models
models01.php
controllers
controller01.php
views
views01.php
‘
‘
and i want use 'models01.php' from module01 , is there any way?
$this->load->model("module01/models01");
You can call any models from any module like this. Tested.
add module name followed by model name, make sure every word is in small.
I resolved my issue by using this piece of code.
$this->load->model('settings/settings_model','settings_model');
In my case using $this->load->model("module01/models01"); not worked,
But after debugging for couple of hours i have found the solution which is as below, i will explain it using the same example as Questioner:
So the solution not working in my case because i have module name as Module01 (first letter was capital in my directory name) and even if i use the same while loading model like $this->load->model("Module01/models01"); it wasn't working.
Then after trying lots of different cases i have found the solution that worked and want to share some of the rule which we have to follow if we are working in hmvc in codeigniter and loading multiple models in one controller which are as follows:
Names of the Directories in modules folder must be in lowercase (should be like module01 not Module01.)
The 1st letter of the controller and model files name have to be the uppercase like Module01 and Models01(see below example).
The 1st letter of the class name of the controller and model must be in uppercase like
// module01/Module01.php
class Module01 extends MX_Controller {
//some code
}
// module01/Models01.php
class Models01 extends CI_Model {
//some code
}
$this->load->model('module/Modelname','alise');
Remember 1st Letter should be Capital for the Model Name
$this->load->model("module01/Models01",'models01');
$this->models01->function_name();

CodeIgniter - where to put functions / classes?

Am having problems understanding where classes should be kept in CI. I am building an application that describes / markets mobile phones.
I would like for all of my functions (i.e. getphone, getdetails etc.) to reside in one class called Mobile - I understand that this file should be called Mobile.php and reside in the controllers folder.
Can I then have multiple functions inside Mobile.php? E.g.
public function getphone() {
xxx
xx
xx
}
public function getdetails() {
xxx
xx
xx
}
Or do I need to put each function in its own class?
I'd really appreciate looking at some sample code that works. I've been going through the documentation and google for a few hours, and tried all sorts of variations in the URL to find a test class, but without much luck! I've even messed around with the routes and .htaccess...
All I am trying to achieve is the following:
http:///model/HTC-Desire/ to be re-routed to a function that accepts HTC-Desire as a parameter (as I need it for a DB lookup). The default controller works fine, but can't get anything to work thereafter.
Any ideas?
Thanks
Actually it works like this:
Controllers and Models go to their perspective folders as you know it
If you want to create functions that are not methods of an object, you must create a helper file. More info here :
http://codeigniter.com/user_guide/general/helpers.html
Now if you want to create your own datatypes (classes that don't extend Models and Controllers), you add them to the library folder. So if let's say you want to create a class "Car" you create this file:
class Car{
function __construct(){}
}
and save it in the libraries folder as car.php
To create an instance of the Car class you must do the following:
$this->load->library('car');
$my_car = new Car();
More information on libraries here:
http://codeigniter.com/user_guide/general/creating_libraries.html
Yes, you can have as many functions in a controller class as you'd like. They are accessible via the url /class/function.
You can catch parameters in the class functions, though it's not advisable.
class Mobile extends CI_Controller{
public function getPhone($phoneModel=''){
echo $phoneModel;
//echo $this->input->post('phoneModel');
}
}
http://site.com/mobile/getPhone/HTC-Rad theoretically would echo out "HTC-Rad". HOWEVER, special characters are not welcome in URL's in CI by default, so in this example you may be met with a 'Disallowed URI characters" error instead. You'd be better off passing the phone model (or any other parameters) via $_POST to the controller.
Classes can exist both as Controllers and Models, as CodeIgniter implements the MVC pattern. I recommend reading more about that to understand how your classes/functions/etc. can best be organized.
Off the top of my head, Pyro CMS is an application built with CodeIgniter and the source code is freely available. I'm sure there are others.
I think it's best you handle it from one perspective, that is; create a utility class with all your functions in it.
The answer to the question of where to put/place the class file is the "libraries" folder.
This is clearly stated in the documentation. Place your class in the libraries folder.
When we use the term “Libraries” we are normally referring to the
classes that are located in the libraries directory and described in
the Class Reference of this user guide.
You can read more on creating and using libraries Creating Libraries — CodeIgniter 3.1.10 documentation
After placing the newly created class in the libraries folder, to use just simply load the library within your controller as shown below:
$this->load->library('yourphpclassname');
If you wish to receive several arguments within you constructor you have to modify it to receive an argument which would be an array and you loading/initialization would then be slightly different as shown below:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('yourphpclassname', $params);
Then, to access any of the functions within the class simply do that as shown below:
$this->yourphpclassname->some_method();
I hope this answers your question if you have further question do leave a comment and I would do well to respond to them.

Resources