DrJens
DrJens

Reputation: 23

PHP - making different classes work seamlessly together

I have a class that will handle user profile operations in an API. The structure of the API files are API Name / version / resource.php. Same structure is used for the namespaces.

I have downloaded a library that will create identicons as default profile pictures. Of course this library contains classes of their own.

My question is, what is the best practice to incorporate this library into my profile class? To keep the classes loosely coupled, I guess calling the external library from within the resource.php is a bad idea? Should it be passed as an argument to the constructor from the php file that will instantiate the API-class? Should the library objects be assigned to properties in the API-class?

Thanks!

Upvotes: 2

Views: 67

Answers (1)

Emile P.
Emile P.

Reputation: 3962

I recommend creating a ProfilePictureService and injecting that to the controller using a dependency container (e.g. PHP-DI).

Your controller will look something like this:

class ProfilePictureController
{
    /**
     * @var ProfilePictureService
     */
    private $profilePictureService;

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

    public function handleUpload(Request $request)
    {
        $this->profilePictureService->handleUpload($request->getUser(), $request->getProfilePictureUpload());
    }
}

Upvotes: 1

Related Questions