Reputation: 4783
I am working on some legacy code which has Controller
class which extends Laravels native Controller
. Inside that class I have constant statuses:
class Controller extends \Controller
{
const STATUS_SUCCESS = 'success';
const STATUS_ERROR = 'error';
....
Fist thing that bothers me is the fact that there are statuses inside a controller class, and I don't think they should be there by good design, but rather on some other ControllerStatus
class.
Another thing about it is that those statuses are repeated in several unrelated classes, so I am wondering if it is a good practice to make a generic class Status
which will hold possible statuses?
The possible issue I see here is that every class that needs to return a status now in return instead of being coupled only to say Controller
, needs to be coupled with Status
as well.
How would I best approach this?
Upvotes: 1
Views: 2842
Reputation: 2277
If constants are being used globally then storing them in config files is a simple and effective solution.
You should create a new file as constants.php
In that file, you can write an array of a constant which you need to use throughout your application and you can easily add new constants in that file.
return [
'status' => [
'status_success' => 'success',
'status_error' => 'error',
'status_abort' => 'abort',
]
];
And you can access them as mentioned below
Config::get('constants.status');
// or if you want a specific one
Config::get('constants.status.status_success');
As you have said using class is also fine but you have to import that class everywhere and if you are using lot of constants in your application then you will end up creating the separate class for different constants.
But in my personal openion using this Config::get('constants.status.status_success');
looks good and your code becomes self documenting.
A programmer should write a code which is self-documenting. Also you can easily add new constants so you can use Config::get('constants.pay_type.visa');
But in the end, decide what is beneficial in your application and use that.
Upvotes: 1
Reputation: 3205
You could perhaps use an interface to ensure that all required controllers have the same constants?
Pros and Cons of Interface constants
The only alternative is making an Abstract class that extends the base Laravel controller which contains your constants, and then you extend that abstract class?
Upvotes: 0