PHP5 Object Oriented Programming

I started creating several applications using OO programming in PHP, but I'm not sure if I am doing this in a standard way.

Here is an example if I had a book class

    class book{

            private $name;
            private $id;
            private $isbn;
    }

There are two scenarios: one, I want to add a new book to my database ...

should I use a function in my new class to create a new book ... i.e.

    $book = new book;

    $book->addAsNew($name, $isbn);

Or should I B) have a function completely independent of the class adding the new book?

Secondly .. when opening my book class, should I have A) constructor

    function __construct( $bookId ){

            //Call mysql DB and set $name and $isbn var based on $bookId

    }

    ...

    $book = new book( $bookId );

of whether b) should have a separate function.

    class book{

            private $name;
            private $id;
            private $isbn;

            public initiated = 0;

            function initiate( $bookId ){

                    //Load $name and $isbn from DB based on $bookId

                    $initiated = 1;
            }
    }

    ...

    $book = new book;

    $book = initiate( $bookId );

Is there a standard way that most programmers could do this? or is it just mostly at the discretion of the programmer?

+3
source share
3 answers

,

book = new Book($name, $isbn). 

, , factory .

B. DB . BookData, factory. . , , factory , , , OO.; -)

+6

, , , :

, , - . :

$book = new Book();
$book
    ->setName($name)
    ->setId($id)
    ->setISBN($isbn);

$bookDataMapper = new BookDataMapper();
$bookDataMapper->save($book);
+1

You can do both!

Initiation call from constructor

function __construct( $bookId = null) {
   if ($bookId) {
      $this->initiate($bookId);
   }
}

From an OOP point of view, this is good because it prevents an empty object.

empty object: An object that is not yet a real living object, but exists only in code.

But since the $ bookId parameter is optional, an empty object is still possible, which allows you to create a new book (record) with a book class.

+1
source

All Articles