Onyx
Onyx

Reputation: 5772

Where do I place a function which I would like to use in multiple controllers and not just in the controller in which I've created it?

Imagine I have 2 controllers, UserController and PostController, however, I want to use a function which has a general use and doesn't thematically belong to any of those classes. Something like:

public function sum($numberOne, $numberTwo) {
    return $numberOne + $numberTwo;
}

Where am I supposed to create it in order to be able to use it in both UserController and PostController? I constantly read that it's a bad practice to call a controller method from another controller but I just can't figure out what's the alternative.

I could just create the function in each controller but then I'd be repeating myself and the code won't be easily maintainable.

Upvotes: 0

Views: 63

Answers (2)

Dave
Dave

Reputation: 908

I create a Helpers folder in these cases inside the App folder. Then namespace the helpers. ie:

A Dates helper App\Helpers\Dates.php


namespace App\Helpers;

/**
 * collection of methods for working with dates.
 */
class Date
{
    /**
     * get the difference between 2 dates
     *
     * @param  date $from start date
     * @param  date $to   end date
     * @param  string $type the type of difference to return
     * @return string or array, if type is set then a string is returned otherwise an array is returned
     */
    public static function difference($from, $to, $type = null)
    {
        $d1 = new \DateTime($from);
        $d2 = new \DateTime($to);

        $diff = $d2->diff($d1);

        if ($type == null) {
            //return array
            return $diff;
        } else {
            return $diff->$type;
        }
    }
 }

Then in any class import the namespace:

use App\Helpers\Dates;

Then call the class

Dates::difference($from, $to);

This way I can create as many helper classes as I need, If I keep reusing the same classes over and over then it makes sense to create a package for them so they can be used on multiple projects.

Upvotes: 2

Source Edin
Source Edin

Reputation: 101

For this you usually create Repositories. For example UserRepository, or CommonRepository. Then in controller that you want to use functions from that Repository you access it like>

$this->CommonRepository->sum($num1, $num2);

Of course you need to include in top on in your constructor that repository like so:

public function __construct(ExampleRepository $ExampleRepository)
    {
        $this->ExampleRepository= $ExampleRepository;
    }

Repositories are usually in app>Repositories>ExampleRepository.php

Hope it helps :D

Upvotes: 0

Related Questions