pedromlpinheiro's avatar

Code class object vs Database object

Hi,

What is consider the best practice when handling objects. What I mean is, should I create a class and instanciate the number of objects that I want or should I have a dedicaded table on my db for that list of objects?

Basic example, should I have a class car and instanciate all the car types that I need or should I have it in a db table to retreive?

Hopefully I'm making myself clear. I'm not sure what is the best practice here. In my current project I used the class approach because It looked easier to add new "cars" whenever I wanted. But on the other hand I have not been seeing people use with approach, atleast in laravel. I might be missing something.

Thank you!

0 likes
10 replies
Mahmoud04's avatar

In my opinion If your car types are static, using a class or Enum might be appropriate. If you need to query, sort, or update dynamically, use a database table. Most people use database methods because they provide flexibility and scalability.

2 likes
jj15's avatar

Are you able to share a short, concrete example from your project? It would make it easier to see exactly what you're trying to accomplish as it can depend.

Going along with the car example for now. If you were building an application that listed all of the cars available for sale by a specific entity, you could indeed create a class that represents the types of cars available (by this I mean sedans, hatchbacks, convertibles, etc.) and instantiate them for use in your controller/view.

It's common to use a PHP enum to store closed, static sets of possible values like the above. However, it might make more sense to instead to store them in the database if they're frequently changing and you don't want to update your code each time or you want to store other data related to the type.

2 likes
martinbean's avatar

@pedromlpinheiro I don’t really understand what you’re asking? You would instantiate objects as and when you need them.

If you need to list all cars, and the cars are stored in the database, then yes, you would fetch the cars from the database and you would have an Eloquent model class instance representing each car that came from the database:

$cars = Car::query()->get(); // Get all cars from database

If you only need one car, then you’d only have one instance:

$car = Car::query()->find(2); // Find car with primary key value of '2'

However, a car is usually a combination of a make (manufacturer, i.e. BMW) and model (i.e. Z3). So I’d personally have a database table representing car manufacturers, and then each row in my cars database table would have a foreign key pointing to the manufacturer:

class Car extends Model
{
    protected $fillable = [
        'model',
        'release_date',
    ];

    public function manufacturer(): BelongsTo
    {
        return $this->belongsTo(CarManufacturer::class);
    }
}

You would then iterate over cars like this:

<ul>
    @foreach($cars as $car)
        <li>
            {{ $car->model }} is made by {{ $car->manufacturer->name }}
        </li>
    @endforeach
</ul>
1 like
pedromlpinheiro's avatar

thank you all for the replies! @malmalah0 @jj15 @martinbean

Below is the way that I did it. (don't mind the names :D I'm practicing using a RPG browser game example).

I also didn't do it on the model file, which probably would be the better practice.

Can you guys tell me if this is fine or am I just overthinking the implementation?

class RobberyService { public $id; public $name; public $stamina; public $reward; public $intelligence; public $tolerance; public $strength; public $charisma; public $currency; public $robbery_power; public $rewardRange; public function __construct($id, $intelligence, $tolerance, $strength, $charisma, $name, $stamina, $reward, $robbery_power, $rewardRange) { $this->id = $id; $this->intelligence = $intelligence; $this->tolerance = $tolerance; $this->strength = $strength; $this->charisma = $charisma; $this->name = $name; $this->stamina = $stamina; $this->reward = $reward; $this->robbery_power = $robbery_power; $this->rewardRange = $rewardRange; }

public static function getAllRobberyJobs(){

    $granny = new RobberyService(1,2,2,2,2, 'Granny', 0.05, rand(50,125), 2, '50$-125$');
    $gasStation= new RobberyService(2,4,4,4,4, 'Gas Station', 0.05, rand(125,250), 8, '125$-250$');
    $shopLifting = new RobberyService(3,4,4,4,4, 'Shop Lifting', 0.1,  rand(250,750), 16, '250$-750$');
    $taxi = new RobberyService(4,6,6,6,6, 'Taxi', 0.1,rand(750,1250), 40, '750$-1250$');
    $allRobberyJobs = [$granny, $gasStation, $shopLifting, $taxi];
    return $allRobberyJobs;
}

}

jj15's avatar

@pedromlpinheiro

You're welcome and thank you for sharing some of your code. I like the idea :)

In your case, creating and instantiating objects one by one seems fine for the current scope of your application. However, a "service" class (at least in my opinion) doesn't typically hold data, it operates on data usually held by another object, such as a model. But you could argue against this for the sake of simplicity since you don't have any models right now.

Now, in a real-world application. Using models and a database would typically be the way to go for most data you'll want to persistently store. For your current needs, you might consider using a package like Sushi that allows you to store your hardcoded data within your model class. It uses SQLite under the hood, which doesn't require a separate database server.

1 like
pedromlpinheiro's avatar

@jj15 I really appreciate the help! You helped a lot, thank you!

Sushi looks exactly what I needed to do! Didn't know about it.

Also, I agree, in a real-world app I would probability go with the db.

Again, thank you!

jj15's avatar

@pedromlpinheiro You're welcome! I'm glad that I and others could help guide you in the right direction. Best of luck with your project (and future ones :).

1 like
martinbean's avatar

@pedromlpinheiro I’m looking at the code sample as there seems to be a couple of code smells.

You have a class that’s taking a lot of parameters. A lot of those parameters are of the same type (lists of integers, i.e. 1,2,2,2,2). What do those integers actually mean? Will you remember the parameter order in a couple of months’ time without opening the class and reading its constructor? Will you be able to remember what 2 means for the third parameter, again without opening the class and inspecting its internals?

When you have more than five or so parameters, that’s usually a sign that you‘re missing something that can be represented as its own object(s). And when you’re just passing plain integers around as parameter values (i.e. 1, 2, 4) they’re referred to as “magic numbers”, because they have an inherent meaning that isn’t immediately visible without digging further into the code. You can avoid this by using constants or enums.

Finally, even though you’ve not properly formatted your code, I can see you’re mixing casing. For example, you flip between snake_case (i.e. $robbery_power) and camelCase (i.e. rewardRange). Stick to one. The prevalent convention in modern PHP projects is camelCase for variable, property, and method names.

2 likes
pedromlpinheiro's avatar

@martinbean

Sorry for the late reply. I really appreciate the time you took for giving some great feedback!

Learned a lot with you! Make sense what you said, the readibility is awful.

Thank you!

1 like

Please or to participate in this conversation.