Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which class does this method belong?

Tags:

oop

php

I'm rather new to OOP and have a general question.

Imagine I have two classes: AddressBook and Contact. An address book contains 0-n contacts.

Where would you put the method getAllContactsFromAddressBook()?

class AddressBook {
    private $addressBookId;

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

    // HERE?
    // getAllContactsFromAddressBook() { ... }
}

and

class Contact {
    private $contactId;

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

    function getContactDetails($contactId) { ... }

    // OR BETTER HERE?
    // getAllContactsFromAddressBook($addressBookId) { ... }
}

What is the best practice in such situations? Thank you for your explanations!

like image 994
Lionel Avatar asked Feb 06 '26 17:02

Lionel


1 Answers

I would put inside class AddressBook the method getAllContacts.

Just try do read how the function call would look like

$addressBook = new AddressBook();
$addressBook->getAllContacts();

The contacts belong to the address book, so you ask to the address book to give you his contacts.

like image 130
Alessandro Avatar answered Feb 09 '26 05:02

Alessandro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!