Object oriented design

I designed the site locally in PHP 5, but ran into several design problems that I would like to get right now.

There are currently three site functions, and each function has a class. These functions are as follows:

  • the blog
  • Friend list
  • image set

I have a class for everyone, but in each class I basically define a similar method that everyone gets [blogs | Friends | images]. I was wondering if any of you know how I can reduce these classes to be much thinner and probably have one class that is common to all three functions for all methods that are the same for each function. (i.e. getAllById ($ feature, $ id)).

An example function for my existing blog class is as follows:

function getBlogsByUserId($userId) {
    global $db;
    $blogs = array();
    $db->where(array("userId"=>$userId));
    $rows = $db->get("blog")->fetch(0);
    foreach($rows as $row) {
 $blog = new Blog();
 $blog->id = $row['id'];
 $blog->userId = $row['userId'];
 $blog->content = $row['content'];
 $blogs[] = $blog;
    }
return $blogs;
}

. , .

, . , , , , .

, Matt

+3
3

, , , Model, :

abstract class Model {
  protected static $_featureTable;

  static public function getAllById($id) {
    global $db;
    $items = array();
    $db->where(array("userId"=>$userId));
    $rows = $db->get(self::$_featureTable)->fetch(0);
    foreach($rows as $row) {
      $item = self::getInstance();
      $item->setValues($row);
      $items[] = $item;
    }
    return $items;
  }

  abstract static protected function getInstance();
  abstract protected function setValues($row);
}

class Blog extends Model {
  protected static $_featureTable = 'blogs';

  protected static function getInstance() {
    $self = __CLASS__;
    return new $self();
  }

  protected function setValues($row) {
    $this->content = $row['content'];
    // etc.
  }
}

, :

$blogs = Blog::getAllById($id);
+1

, ORM, Doctrine Propel. .

, , , Doctrine , , ( ).

+1

You can create an object / function with a parameterizable Factory. It will aggregate the function 'row_to_object' and the request object:

function row_to_blog( $row ) {
    return new Blog( $row["id"], $row["title"] );
}

function create_from_query( $query, $row_to_object ) {
    $objects=array();
    foreach( $row as $db->fetch( $query ) ) {
       $objects[]=$row_to_object( $row );
    }
    return $objects;
}

$query=new Query( "blogs", new Where("userid",$id) );
$blogs=create_from_query( $query, row_to_blog );
0
source

Source: https://habr.com/ru/post/1725869/


All Articles