Yahav's avatar
Level 3

PHP Classes and good practice question

So, this question is about structure and good practice.

say i have a class named: "YouTubeProcessor" which object is to fetch videos by channel and analyze them. So, at the constructor i''m passing the configs required to the class:

$youtube = new YouTubeProcessor($YouTubeConfigurationObject);

now, inside the class i have a private var ($YouTubeConfiguration) which i set at the constructor:

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

So far i assume its all good practice?

now, i need to create a new google api client and here's my question: do i create it at the constructor and pass it to other functions or create a class variable and put the created object in there? so basically its:

public function __construct(YouTubeConfiguration $YouTubeConfigurationObject)
    {
        $this->YouTubeConfiguration = $YouTubeConfigurationObject;

        $client = new Google_Client();
        someFunction($client);
    }

or

private $googleClient;
....
public function __construct(YouTubeConfiguration $YouTubeConfigurationObject)
    {
        $this->YouTubeConfiguration = $YouTubeConfigurationObject;

        $this->googleClient = new Google_Client();
        someFunction();
    }
protected function someFunction()
{
    /// using $this->googleClient;
}

which one is better/considered better practice? does it even matter?

0 likes
2 replies
Talinon's avatar

I would go with the second option and make it a class private/protected property. This way, you can reference it anywhere within your class without the need of passing it through method calls.

I'm sure it was just an oversight, but you would also want to call $this->someFunction()

Yahav's avatar
Level 3

Thanks Is it up to me or there is the "good" way and the "bad"way?

Please or to participate in this conversation.