V
V
Vladimir Krygin2020-06-12 11:42:45
PHP
Vladimir Krygin, 2020-06-12 11:42:45

Is it normal to access methods and properties of classes through a single service?

Good afternoon!
There is a service class through which the properties and methods of other classes (models) are accessed. Implemented like this:

namespace App\Services;

use App\Models\City;
use App\Models\Country;
use App\Models\Hotel;
use App\Models\Region;

class Service
{
    private Country $country;
    private City $city;
    private Hotel $hotel;
    private Region $region

  /**
     * @param $name
     * @return City|Country|Hotel|Region
     * @throws \Exception
     */
    public function __get($name)
    {
        switch ($name) {
            case 'country':
                return new Country();
            case 'city':
                return new City();
            case 'hotel':
                return new Hotel();
            case 'region':
                return new Region();
            default:
                throw new \Exception('Property ' . $name . ' is not exist.');
        }
    }
}

The calls go like this:
$service = new Service();
$some = $service->city->someMethod();
$field_name = $service->country->field_name;

The question is, how reasonable is this approach, and maybe. are there any pitfalls?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2020-06-12
@Mercury13

From my belfry of static languages, such a construction is excessive complexity from scratch.
But there are places where such complexity is also somehow justified. For example, Qt - the contents of a table cell ...

QVariant SomeModel::data(
    const QModelIndex &index, int role = Qt::DisplayRole) const override {}

What is it for in Qt…
• at the very beginning of the function, the address in memory where all this data is located can be calculated, followed by a long switch/case “depending on the role, take this and that”;
• it is possible to return an empty QVariant when it is necessary to say: "act as usual";
• Finally, complex operations with data are possible, such as converting to a displayable form and sorting, which do not depend on the specifics of the data model.
So that's the answer. Look at the place: what do you want to say with this construction and why simpler ones are not justified.

A
Anton Shamanov, 2020-06-13
@SilenceOfWinter

congratulations, you discovered the facade design pattern

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question