Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uros23's avatar

Hardcoding some logic (if that makes sense?)

This is the current status:

We have an Agency model which has a "type" field. Because we will have a finite number of types, and we will not be adding any new ones after the initial setup of the app, i got the task of hardcoding the "agency_type" ids to specific meanings.

Why am i supposed to do this? Because we have just a few types, and it will be faster for it to be hardcoded into php with a function that just returns a string if input a number (e.g.

agency_type($id) {
    if ($id == 1) {
        return 'type1'
    } else ($id == 2) {
        return 'type2'
    }
    etc...
}

), than to have it in a database.

Should i do this using services, helper functions or something else? What would be the pros and cons of going either way? Is there something i'm missing?

0 likes
4 replies
slashequip's avatar
Level 6

I'd use some form of Support class and store the types as an array.

<?php
namespace App\Support

class AgencyType
{
    private $types = [
        1 => 'type1',
        2 => 'type2',
        //etc...
    ];

    public function find($id)
    {
        if( isset($this->types[$id]) ) {
            return $this->types[$id];
        }

        throw new \Exception('Type does not exist');
    }
}

Having it a class is more Object Orientated also it does give you the flexibility to update your types in the future (I know you said you don't need to but there is probably a good chance you will in the future).

You can now also add a method for getting all the available types to use in a form etc and it is all managed from one place.

uros23's avatar

Thanks for the fast reply.

How about a static array in the model like this:

class Agency
{
    // some code here ...

    public static $agency_type = ['type1', 'type2', 'type3'];

}

This way, if i need it, i can just use the id of the 'agency_type' field as the index for the array like so:

public function show($id)
{
    $agency = Agency::find($id);
    $agency_type = Agency::$agency_type[$agency->type - 1];
}

Do you see any downsides to this in the long run?

lostdreamer_nl's avatar

@uros23 There is no problem with having it in the Agency model itself, but I would really stress the need to have it with the keys as haganjones said

(What would happen in your case is: if you have to delete type1 at some point, The ID for all others will change as well.)

uros23's avatar

@lostdreamer_nl thank you very much.

In the end, that's what I did. Used an associative array to store these types so even if I were to delete (which I won't) some of these types, the referential integrity will be maintained.

Please or to participate in this conversation.