How to declare "sub-objects" in PHP

I'm relatively new to OOP in PHP, and I'm not sure what I'm trying to do is possible or recommended. In any case, I can’t figure it out. I would appreciate any guidance on tutorials or documents that could help - I do not expect a complete answer here.

I have a system in which each user has several "libraries". Each library contains several "Elements".

Database setup is as follows:

user_libraries
 - id (unique)
 - user_id (identifies user)
 - name (just a string)

elements
 - id (unique)
 - content (a string)

library_elements
 - id (unique)
 - library_id
 - element_id

where library_idis id from user_libraries, and element_idis from elements.

I want to have access to this user library and their elements.

I installed a library class and can use it to retrieve a list of libraries (or a sub-list).

I do it like this:

$mylibraryset = new LibrarySet();
$mylibraryset->getMyLibraries();

( print_r):

LibrarySetObject (
 [user_id] => 105
 [data_array] => Array (
  [0] => Array (
   [id] => 1
   [user_id] => 105
   [type] => 1
   [name] => My Text Library
  )
  [1] => Array (
   [id] => 2
   [user_id] => 105
   [type] => 2
   [name] => Quotes
  )
 )
)

, , ( data_array), .

, , - :

foreach($mylibrary->data_array as $library) {
 $sublibrary = new Library();
 $sublibrary -> getAllElements();
}

Sublibrary - , getAllElements. , , , ...

, - :

$mylibrary->sublibraries[0]->element[0]

?

, - , .

+5
1
<?php

class Library {
    public $element;
    public $data;
    public function __construct($sublibrary) {
        $this->data = $sublibrary;
    }
    public function getAllElements() {
        // populate $this->element using $this->data
    }
}

class LibrarySet {
    public $user_id;
    public $data_array;
    public $sublibraries;
    public function getMyLibraries() {
        // populate $this->data_array

        $this->sublibraries = Array();
        foreach($this->data_array as $index => $sublibrary) {
            $this->sublibraries[$index] = new Library($sublibrary);
            $this->sublibraries[$index]->getAllElements();
        }
    }
}

$mylibraryset = new LibrarySet();
$mylibraryset->getMyLibraries();

$mylibraryset->sublibraries[0]->element[0]

?>
+2

All Articles