Is my file/class naming convention OK for codeigniter? - php

I am starting a new project and want things to be done right:
Controller:
file name: routemanagerdashboard.php
class name: RouteManagerDashboard
Views:
file name: routemanagerdashboard_dashboard.php
Model:
file name: routemanagerdashboard_model

These naming conventions are perfectly fine. Although there are some conventions you must follow, what you name your files/classes mostly comes down to personal preference. After working with CodeIgniter for a couple years I've settled on the following naming conventions for my files.
Controllers: companies.php (plural file and class name)
Models: company_model.php (singular of the table it corresponds to)
Views: companies/method_name.php (all views for the controller go into a folder for views in that class)
I always make my database table names plural and have a one-to-one relationship between my models and tables. Controllers usually have a corresponding table and model, but not always. I also use a base model which removes a lot of the tedium of setting up a new model for every table which fits into this setup very well and is probably a big reason that I stick pretty strictly to it.

This is fine, but routemanagerdashboard seems a bit verbose, you may consider coming up with something shorter. If you like the controller class name but hate the long urls, you can always use a route to get around it.
Since we're dealing with PHP, case sensitivity is not an issue, so your controller class name is fine, just as long as it matches the characters in it's file name. Just stick to lowercase file names.
Your model name is using the common CI convention, but be aware that when loading the model you may use the second parameter to alias the class name for easier use. Example:
$this->load->model('routemanagerdashboard_model', 'r_model');
$this->r_model->get_something(); // A little easier to work with
On views: It's probably better to create a subdirectory for all views that are directly related to the controller. You are probably going to need more than just one view file per controller. You will see your /views folder become unmaintainable if you put all view files directly in the root of it. I suggest you use sub directories and short meaningful file names, perhaps matching the name of the controller method you intend to load them in. Example:
// file = /views/routemanager/dashboard.php
$this->load->view('routemanager/dashboard');
So, yes - you're Doing it Right for the most part, but coming up with shorter names if possible, and organizing your view files into subdirectories will probably be a good idea.

Related

Efficient way to organize View files in Laravel 5.3 when coding with PhpStorm

I don't know if this question qualifies to be in SO, but since PhpStorm became de facto the IDE to develop in Laravel framework, this could be helpful to many of us. Since file naming in Laravel is a big deal, I was wandering what would be a proper/efficient/logical way to name View files.
Lets say I declare all my routes in web.php. I have multiple tables, all named as word in plural like articles. So I have Article model and ArticleController resource controller. Controller consist of standard RESTful and nonstandard routes.
The way I wanted to name my View files is pretty much straightforward and logical, eg:
for home in web.php I have /resources/views/home.blade.php and define it with view('home')
for index in ArticleController I have /resources/views/articles/index.blade.php and define it with view('articles.index')
for show in ArticleController I have /resources/views/articles/show.blade.php and define it with view('articles.show')etc...
Problem arise when I want to use famous PhpStorm CTRL+SHIFT+N open by file search, I get filenames with the same filename, like show.blade.php. As far as I know, there is no way to search by a path name...
So, I decided to rename my filenames to articles_show.blade.php, articles_index.blade.php, but pretty soon I my views folder was overcrowded. I have considered articles/articles_show.blade.php pattern, but it's not following DRY principle and look ugly when defined.
Do any of you managed to develop a solution for efficient and logical naming convention? How do YOU organize your view files?
P.S. I still use original pattern for vendor views, like auth/login.blade.php, auth/register.blade.php. Layouts files also follows that pattern: layouts/app.blade.php (popular layout name), layouts/header.blade.php, layouts/footer.blade.php. But it's obvious, these filenames will not be repeated, so no problem with search function. I want to also mention, that for most tables/controllers/models I have a special loop view file, that is not bound to any function or route, and named by established pattern, like articles_loop.blade.php.
It looks like you can search for a filename by a path! Kudos to #LazyOne, since he pushed me in the right direction.
So, in order to search for a filename within a path using a partial match, all you need to do is suffix a partial path name with "/" and type in a partial of your filename.
So in order to find /resources/views/articles/show.blade.php, you can put either:
ar/sh
vi/ow
ar/shbl (notice how I used two partial sh and bl to find show.blade.php without any separator whatsoever).
etc..

Controllers naming convention in Laravel 5

All controllers in Laravel 5 are still named with Controller suffix, like AuthController and PasswordController. Is there any reason to follow this convention with own controllers, or are those suffixes just leftovers from pre-namespacing era?
I use action-based URL generation most of the time, so I avoid linking like url('home'), but prefer something like action('HomeController#index) instead. This way I can change URL patterns without a headache.
But action('Home#index') is so much more elegant. Any traps behind it?
There's no need to add the Controller suffix. If it was really needed, when you create a Controller through artisan, it would automatically add it, or complain about it, and it is not. So, feel free (but keep in mind that if you want a controller "Dog" and there is a model "Dog"... well, it will be complicated).
No need of adding Controller Suffix. It is just user recognition. So that we can easily get that is an controller. You can normally create Home instead of HomeController. And action('Home#index') will perfectly work. But models in Laravel is something different. If your model name is in singular your table name will be plural. And this is also not a compulsory thing. But if we add Controller in suffix it would be best in using controller and model. Because we will add use home and use app\home in the controller. This would confuse us.
Having Controller at the end of every controller class name does feel like a type of Hungarian notation. However, a class's name should tell the programmer quickly and unambiguously what it does. A DogController is not a Dog. In fact, I can't think of a better name than DogController for it.
Yes, it is namespaced as App\Http\Controllers\DogController which seems like double handling, but how often do you think about or refer to a class by its fully qualified name? Most often a class is referred to just by its class name, and PHP even allows you to do this in code with use App\Http\Controllers\DogController; which will make DogController a valid class name in your code.
That being said, Laravel will not force you to use this convention. If you are working with other programmers you need to have an agreed naming convention, and using Laravel's is the easiest as well as the one most Laravel programmers will already be familiar with.

Avoiding _model suffixes in CodeIgniter

If you're like me, you think CodeIgniter is pretty nice. You also probably hate typing _model every time you load or call a method or property from your models, because it's ugly and time-consuming.
I've been searching for a solution to this for a couple hours with no luck - so I put together a quick fix.
Take a look at the loader class documentation.
Say you've got a class called page_model, you would typically load and use it like this:
$this->load->model('page_model');
$this->page_model->function();`
If you want to avoid typing _model every time you can do this:
$this->load->model('page_model', 'page');
$this->page->function();
When I first started using CodeIgniter I always did this. Now after using CI for several years and a number of websites, I regret that decision.
It's harder to tell what's going on when looking at the code. Having the _model as part of the code that calls the model function removes any ambiguity. For example, in the above function call is page a library or a model?
This is because CodeIgniter does not support namespaces. While there have been discussions of namespace support in CI for some time, support in the stock codebase is still forthcoming.
The solution? Prefix your controllers instead! In typical usage, you're unlikely to need to type the name of the controller more than once per file.
First edit application/config/routes and add the following line after all the other routes:
$route['(:any)'] = "c_$1";
With this rule, you route the first segment of the URI to the matching controller with your prefix. So that:
http://www.domain.com/fishsticks
maps to the following controller:
c_fishsticks
Next, rename your controller files with this prefix, as well as altering the class names inside to match.
That's it! Now you can name your models with relative freedom. You can rename your models at your leisure, but don't forget that you need to change each model's filename, each model's class name, as well as all references to each model. This is easily the most time-consuming step, but on the plus side you don't have to do it all at once.

Organizing a PHP project

What It Is
Here is what I've done so far:
core/
controllers/ (contains the controllers used by the app)
models/ (contains the models used by the app)
views/ (contains the views used by the app)
base_controller.php (the controller every other extend)
base_model.php (the model every other extend)
vendors/
phprouter/ (a simple router class)
pimple/ (a simple DI container class)
configuration.php (contains all the app configuration)
index.php (includes the configuration, vendors, base model, base controller, sets the DI container up and route the request)
See the code here: http://pastebin.com/pxUpUvv6
Please note that the given code is just an example, therefore the controllers, models, views aren't in place yet. Also, it may be buggy—as untested—, but it doesn't matter right now.
Request Flow
The client requests index.php.
The configuration, vendors, base controller, base model are included.
The DI container and the dependencies are initialized, we can now inject them anywhere.
We map controllers to URL and the router does its job.
The controller is fetched (although this is not in the example code, as noted above).
We do some stuff.
The method then calls ::call_model(), which includes the corresponding model from core/models/, and then calls the same method we're using from the model class corresponding.
The model is fetched.
More stuff.
The model then calls ::call_view()', which includes the corresponding view from core/views/.
The view is fetched and render the page to the client.
FYI: Corresponding
Examples of controller, model, view which correspond:
Controller Controller_Products::list() at core/controllers/Controller_Products.php
Model Model_Products::list() as core/models/Model_Products.php
View at core/views/Model_Products_list.php
Issues Being Faced
Actually, I feel a bit uncomfortable with this structure. Dunno, it seems to be far from scalable, modulable...
Does only the basic folder structure—core{, /controllers, /models/, /views}, vendors at the root—looks good to you?
I feel like I should get __autoload() outside of index.php, which seems a little too big to me. If so, what about DI container?
Maybe if I get to needing more than two external library, it should be better not to have them included one by one, manually? But how?
Putting all the configuration in a file configuration.php at the root looks to me like old-fashioned PHP4. Thanks to the power of Pimple, I could embed this configuration directly into it but yet, where?
I think the way I handle ::call_model() (core/base_controller.php) and ::call_view() (core/base_model.php) is a bit awkward. Would you agree? What'd be a simplified way to redo the whole thing?
Considering all my issues, would it eventually be better for me to use a framework as Symfony?
If something isn't clear, feel free to ask.
Thanks.
Yes.
You can use autoload and DI container together. There is example, how autoload can be used with naming convention. I recommend to use spl_autoload.
With autoload you can remove all (or almost all) includes.
In index.php, I guess.
Yes, it's wrong way. First of all, try to not use static methods. Also, models should have methods with descriptive names, not just 'call me and I will do all what I can'. It's more complex problem - you need to understand how Controller and Model should do their cooperation. As variant, read some books. Controller should call methods of Model, to get data for some situation. Model it's not just place for code of controller. Different controllers can use different models. Models too can use another models.
Answer to this question can not be objective :)

What do you name your files when using MVC?

When using the MVC pattern, which I'm not terribly experienced with, I find myself naming things like this:
/app/views/widget.php
/app/models/widget.php
/app/controllers/widget.php
That appeals to me because it's easy to find associated classes, and I lean towards shorter names when practical. However, when I'm looking in my IDE, I see three different files called widget.php, which is confusing. I'm tempted to add "_v", "_c", "_m" or something to each name. How do you handle this?
FWIW, I'm using CodeIgniter at the moment, and I don't know if there are any special benefits to using a particular convention, or any standard practices. Regardless, I'm intersted in the best-practices from various platforms.
My view ends in phtml, so that would make Widget.phtml. My model is a Widget so that would yield Widget.php, just like that, and my controller would be WidgetController.php.
I personally think that having everything named widget.php gets confusing even if the files are in separate files. I tend to append either Model, View, or Controller to the end of the files names in addition to having the files divided into respective folders. While it is more verbose it is much more expressive and easier for newcomers to your code base to follow your code. So my widget (in Java which is what I most frequently use for mvc) would be named as follows:
/app/widget/view/WidgetView.jsp
/app/widget/model/WidgetModel.java
/app/widget/controller/WidgetController.java
/app/coolwidget/view/CoolWidget.java
...
Plus when I'm in an IDE or editor I tend to look at the file name and not the full path to the file when editing. So if I'm editing the Model, View, and Controller for my widget, I don't want to be examining the file paths to figure out which one I'm working on.
CodeIgniter (and for that matter any framework) relies on a set of 'conventions' (rules basically). One of those rules is how routing is handled. For example, the 'widget' file you have in /app/controllers/ will translate to a URL of http://yoursite.com/widget/action/ (where action are function names in your Widget class.
The normal convention is to use CamelCaseNaming for your classes and lowerCamelCase naming for methods. Each framework has a different routing engine. If you have class WidgetBlahBlah will translate to a url of /widget-blah-blah/ or /widget.blah.blah/ (depending). Action names and routing are similar.
As for naming of views, views should be named the same as your actions. They should be organized into sub directories based on your class names. Again, this is all convention. Actions in your classes look for views in specific locations named a specific name.
If you're going to use MVC I would suggest going back to the beginning and learning how to use it. MVC is designed to be rapid development by understanding a set of conventions and leveraging them. Maybe start here: http://codeigniter.com/user_guide/toc.html
I generally just leave them named without any special convention, and distinguish between the different files by looking at:
- folder names
- file contents
With syntax highlighting, a view file containing mostly html is very easy to distinguish from a controller or model. As for telling the difference between models and controllers: I don't generally name models and controllers with the same names, so there isn't a problem there for me.

Categories