Welcome Guest, Not a member yet? Register   Sign In
Class naming conventions
#1

[eluser]deed02392[/eluser]
I've noticed I keep on clashing class names, although I feel like what I'm doing makes sense...

I've got a controller which takes all actions to do with stock, 'class Stock extends MY_Controller'.

Then I've got a model which handles all the data input/output to do with stock, obviously:
'class Stock extends CI_Model'.

Then I get the error cannot redeclare class, of course. But surely it makes sense these are both called 'Stock' since that's each what their primary functions pertain to. Surely I'm not expected to name these 'Stock_controller' and 'Stock_model' or something? Some guidance please. Smile
#2

[eluser]LuckyFella73[/eluser]
I would name the controller "stock" and the model "stock_model".
You don't see the model name in your URL like the controller name,
so I don't see a problem naming a model xyz_model.
#3

[eluser]Aken[/eluser]
Stock_model or Stock_m is common for most people.
#4

[eluser]CroNiX[/eluser]
Don't forget, when CI loads a controller, library or model, it extends the singleton, $this, with the name of the object you are loading. So if you load 2 things with the same name, there will be a collision.

As others mentioned, its common to leave the controller name as clean as you can, since that is what will appear in the url, and then add a suffix to everything else that indicates what it is.

User (controller)
User_model (model)
User_library (library)

Then to access,
$this (when in controller)
$this->user_model (when accessing model from controller)
$this->user_library (when accessing library from controller)

You'll never have a collision and everything will make syntactic sense when viewing the code.
#5

[eluser]wiredesignz[/eluser]
@CroNiX, '$this' has nothing to do with any singleton or even the CI super object (controller). Where do you guys get this stuff?

'$this' refers to the current object context.
In the controller it is the controller object, in a model it is the model object and in a library it is the library object.

@deed02392, PHP will not allow two classes with the same class names to exist in the same namespace, it's that simple. It has nothing to do with object naming or even CodeIgniter.

#6

[eluser]CroNiX[/eluser]
You read more into what I wrote than was there.
#7

[eluser]wiredesignz[/eluser]
[quote author="CroNiX" date="1342740505"]... it extends the singleton, $this, with the name of the object you are loading. So if you load 2 things with the same name, there will be a collision....[/quote]

@CroNiX, I read what is there and it's all rubbish!
#8

[eluser]CroNiX[/eluser]
Thanks for sharing your opinion.




Theme © iAndrew 2016 - Forum software by © MyBB