N
N
nepster-web2016-10-05 14:14:11
PHP
nepster-web, 2016-10-05 14:14:11

Who should take on the duty of a helper?

Actually I'm trying to move towards good code and I want to solve the headache with helpers once and for all.
Suppose there is the following situation: You need to render product data in the form.
We have an entity:

class Product {

    protected $name;
    protected $description;
    protected $price;
    protected $amount;

    public function setName($name)
    {
        ...
    }

    public function setDescription($description)
    {
        ...
    }

    public function setPrice($price)
    {
        ...
    }

    public function setAmount($amount)
    {
        ...
    }

    public function getName()
    {
        ...
    }

    public function getDescription()
    {
        ...
    }

    public function getPrice()
    {
        ...
    }

    public function getAmount()
    {
        ...
    }
    
}

All is well, all is well. Now the task is to show the product data on the page. Here the following questions arise:
- Multilanguage (everything is not so bad, we can visit our entity with the necessary data that was obtained earlier)
- Price. For example, I want to see not 1210.23783, but $1,210.24. That is, you will need to use a helper that will convert the float into a readable string.
- Quantity, I want to see the same thing not 435435, but 435,435 units (for example)
Of course, we already have all these helpers and the code in the form may look like this:
<p class="price">{{ Currency::formatString($product->getPrice()) }}</p>

However, it's not always convenient to drag helpers into a view. Especially if some kind of template engine is used, etc.
It would be much more convenient to do something like this:
<p class="price">{{ $product->getPriceString() }}</p>

Where the $product->getPriceString() method returns what we need. There are 2 problems here:
- The entity becomes dependent on the helper.
- What if, for example, the admin panel needs a different display. Well, let's say, if the number is less than 10, then highlight it in red?
Please tell me how it is generally correct to solve such things, separately with helpers in the view, or is it still possible to shove additional methods into the entity?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitriy, 2016-10-05
@dmitriylanets

the data in the model should be as it is, you need to format it at the output level, for
example, there are places where you need to display the date, let’s say in the format dmY H: i and where is dmY, and where in general in Ymd H: i
, you won’t keep 3 methods to display these dates
are better $model->getDateTime()->format("dmY H:i");//where $model->getDateTime() returns a Datetime object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question