Как правильно писатьв объектном стиле

auditseo

Новичок
Добрый день! Прошу посмотреть мой незатейлевый код и сказать нормально ли так писать в ООП стиле или это не в какие рамки не лезет? Интересна конструктивная критика.

PHP:
<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // var_dump($_POST);
    // echo "\n";
    $objProcessingRequest = new ProcessingRequest();
    //$objProcessingRequest->makeRequest();

    $textJson = $objProcessingRequest->getTextJson();
    // echo "JSON\n\n";
    echo $textJson;
}

class ProcessingRequest
{
    private $requestClient = '';
    private $requestClientEncode = '';
    private $finalRequest = '';
    private $appId = 'Q2XYU3-EUU22U5UVX';
    private $responseXml = '';

    private $img3D;
    private $imgContour;
    private $imgExpression;

    private $responseJson = '';

    //формируем запрос на вольфрам
    public function __construct()
    {
        // сначала получим запрашиваемую ф-цию от клиента
        $this->acceptClientRequest();
        //сформируем GET запрос для вольфрама
        $this->createGetRequest();
        //посылаем запрос в вольфрам (CURL)
        $this->sendRequest();
        //распарсим XML
        $this->parseXml();
        //сформируем JSON для отправки клиенту
        $this->createJson();
    }

    // получить у объекта текст XML
    public function getTextXml()
    {
        return $this->responseXml;
    }

    // получить JSON
    public function getTextJson(){
        return $this->responseJson;
    }

    // принимает от клиента запрос - которые переправим на вольфрам
    private function acceptClientRequest()
    {
        // взяли данные из запроса
        $strFunc = $_POST['strFunc'];
        $betweenX_1 = $_POST['betweenX_1'];
        $betweenX_2 = $_POST['betweenX_2'];
        $betweenY_1 = $_POST['betweenY_1'];
        $betweenY_2 = $_POST['betweenY_2'];
        // формируем строку запроса на вольфрам
        //'plot x^2+(y-3)^2-2 over x=-10..10, y=-10..10';
        $this->requestClient = 'plot ' . $strFunc . ' over' . ' x=' . $betweenX_1 . '..' . $betweenX_2 .
            ', ' . 'y=' . $betweenY_1 . '..' . $betweenY_2;
        //debug
        // echo 'request: ' . $this->requestClient . "\n";
    }

    // склеим запрос, который пошлем вольфраму
    private function createGetRequest()
    {
        $this->requestClientEncode = rawurlencode($this->requestClient);
        $this->finalRequest = 'http://api.wolframalpha.com/v2/query?appid=' . $this->appId . '&input=' . $this->requestClientEncode . '&format=image';
        //debug
        // echo $this->finalRequest . "\n";
    }

    //отправляет запрос и получает XML
    private function sendRequest()
    {
        $curl = curl_init();
        if ($curl === false) {
            // echo "Curl error: " . curl_error($curl);
        } else {
            curl_setopt($curl, CURLOPT_URL, $this->finalRequest);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            $this->responseXml = curl_exec($curl);
            curl_close($curl);
        }
        // проверяем была ли ошибка
        if (curl_errno($curl) != 0){
            exit;
        }
        //debug
        // echo '$resposeXml = ' . $this->responseXml . "\n";
    }

    // распарсим XML на ассоативный массив
    private function parseXml()
    {
        $objXml = new SimpleXMLElement($this->responseXml);
        // картинка 3D
        foreach ($objXml->pod as $tagPod) {
            if($tagPod['title'] == 'Input interpretation'){
                $tagImgExpression = $tagPod->subpod->img;
                $this->imgExpression['src'] = (string) $tagImgExpression['src'];
                $this->imgExpression['width'] = (string) $tagImgExpression['width'];
                $this->imgExpression['height'] = (string) $tagImgExpression['height'];
            } elseif ($tagPod['title'] == '3D plot') {
                $tagImg3D = $tagPod->subpod->img;
                $this->img3D['src'] = (string) $tagImg3D['src'];

                //// echo "CHECK!!!\n\n";
                //// var_dump(( (string) $tagImg3D['src']));

                $this->img3D['width'] = (string) $tagImg3D['width'];
                $this->img3D['height'] = (string) $tagImg3D['height'];
            } elseif ($tagPod['title'] == 'Contour plot') {
                $tagImgContour = $tagPod->subpod->img;
                $this->imgContour['src'] = (string) $tagImgContour['src'];
                $this->imgContour['width'] = (string) $tagImgContour['width'];
                $this->imgContour['height'] = (string) $tagImgContour['height'];
            }
        }
    }

    // формируем JSON, который отправим клиенту
    private function createJson(){
        $jsonImg3D = json_encode($this->img3D);
        $jsonImgContour = json_encode($this->imgContour);
        $jsonImgExpression = json_encode($this->imgExpression);
        // var_dump($jsonImg3D);
        // var_dump($jsonImgContour);
        $this->responseJson = "{\"imgExpression\": $jsonImgExpression,\"img3D\": $jsonImg3D,\"imgContour\": $jsonImgContour}" ;
        // var_dump($this->responseJson);
    }
}
 

fixxxer

К.О.
Партнер клуба
Это не ООП, это функции, обернутые в класс.

Но это нормально, у всех сначала так получается. В рамках темы в форуме объяснить невозможно. Надо читать литературу, смотреть, как пишут другие, и "прочувствовать".
 

auditseo

Новичок
Но это нормально, у всех сначала так получается. В рамках темы в форуме объяснить невозможно. Надо читать литературу, смотреть, как пишут другие, и "прочувствовать".
Да, согласен, так как задача была простая, то есть этот код нормален? Какую литературу посоветуете?
 

scorpion-ds

Новичок
Нормальный код, я что-то похожие делал в WP, там по сути ООП нет, но вот подобным образом делать плагины допустимо.

http://www.ozon.ru/context/detail/id/33506422/ - я читал книгу этого автора, только немного долее старое издание.
 

WMix

герр M:)ller
Партнер клуба
__construct() на контроллер похоже
acceptClientRequest(),sendRequest() createGetRequest(), parseXml() где-то на уровне модели, нужно делить на парсер, драйвер, модель, реквест...
createJson() типа вью
 

halva

Новичок
Написано у тебя не правильно потому что ты используешь классы для группировки функций, а ООП это не то. Как минимум классы нужны что бы описывать сущности и действия производимыми с ними. У тебя даже название класса обозначает действие, а должен обозначать существительное. Правильно было бы выделить сущность Transport (которая будет забирать данные через curl), Parser (которая будет декодировать xml в обычный формат) и WolframAlpha (который будет агрегировать Transport, Parse вместе). Можно еще добавит Responder для кодирования полученых данных в json или другой формат

Можно к примеру так все сделать
PHP:
<?php

class WolframAlpha_Transport {

  /**
  * @var string
  */
  protected $baseUrl = 'http://api.wolframalpha.com/v2/query?';

  /**
  * @var WolframAlpha
  */
  protected $wolframalpha;

  public function __construct(WolframAlpha $wolframalpha) {
  $this->wolframalpha = $wolframalpha;
  }

  private function send(WolframAlpha_Request_Plot $request) {
  $curl = curl_init();
  if ($curl === false) {
  throw new Exception('curl failder');
  } else {
  $requestUrl = $this->baseUrl . http_build_query(array(
  'appid' => $this->wolframalpha->getAppId(),
  'input' => $request->getTransportString(),
  'format' => $request->getFormat(),
  ));
  curl_setopt($curl, CURLOPT_URL, $requestUrl);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_HEADER, 0);

  $response = curl_exec($curl);
  curl_close($curl);
  $request->handleResponse($response);
  }

  if (curl_errno($curl) != 0) {
  throw new Exception('curl failder');
  }
  }

}

class WolframAlpha_Request_Plot {

  protected $function;
  protected $beetweenX;
  protected $beetweenY;
  protected $responseHandler;

  public function setFunction($function) {
  $this->function = $function;
  }

  public function setBeetweenX($from, $to) {
  $this->beetweenX = array($from, $to);
  }

  public function setBeetweenY($from, $to) {
  $this->beetweenY = array($from, $to);
  }

  public function getFormat() {
  return 'image';
  }

  public function getTransportString() {
  return 'plot ' . $this->function . ' over' . ' x=' . $this->beetweenX[0] . '..' . $this->beetweenX[1] .
  ', ' . 'y=' . $this->beetweenY[0] . '..' . $this->beetweenY[1];
  }

  public function setResponseHandler($handler) {
  $this->responseHandler = $handler;
  }

  public function handleResponse($response) {
  $this->responseHandler->handle($response);
  }

  public function getResponseHandler() {
  return $this->responseHandler;
  }

}

class WolframAlpha_Response_Xml {

  public function handle($response) {
  $objXml = new SimpleXMLElement($$response);
  // картинка 3D
  foreach ($objXml->pod as $tagPod) {
  if ($tagPod['title'] == 'Input interpretation') {
  $tagImgExpression = $tagPod->subpod->img;
  $this->imgExpression['src'] = (string) $tagImgExpression['src'];
  $this->imgExpression['width'] = (string) $tagImgExpression['width'];
  $this->imgExpression['height'] = (string) $tagImgExpression['height'];
  } elseif ($tagPod['title'] == '3D plot') {
  $tagImg3D = $tagPod->subpod->img;
  $this->img3D['src'] = (string) $tagImg3D['src'];

  //// echo "CHECK!!!\n\n";
  //// var_dump(( (string) $tagImg3D['src']));

  $this->img3D['width'] = (string) $tagImg3D['width'];
  $this->img3D['height'] = (string) $tagImg3D['height'];
  } elseif ($tagPod['title'] == 'Contour plot') {
  $tagImgContour = $tagPod->subpod->img;
  $this->imgContour['src'] = (string) $tagImgContour['src'];
  $this->imgContour['width'] = (string) $tagImgContour['width'];
  $this->imgContour['height'] = (string) $tagImgContour['height'];
  }
  }
  }

  private function toJson() {
  $jsonImg3D = json_encode($this->img3D);
  $jsonImgContour = json_encode($this->imgContour);
  $jsonImgExpression = json_encode($this->imgExpression);
  // var_dump($jsonImg3D);
  // var_dump($jsonImgContour);
  $this->responseJson = "{\"imgExpression\": $jsonImgExpression,\"img3D\": $jsonImg3D,\"imgContour\": $jsonImgContour}";
  // var_dump($this->responseJson);
  }

}

class WolframAlpha {

  protected $appId;

  public function getAppId() {
  return $this->appId;
  }

  public function setAppId($appId) {
  $this->appId = $appId;
  }

  public function __construct() {
  $this->transport = new WolframAlpha_Transport($this);
  }

  public function doIt($params) {
  return $this->transport->send('plot');
  }

}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $wa = new WolframAlpha();
  $wa->setAppId('Q2XYU3-EUU22U5UVX');

  $plot = new WolframAlpha_Request_Plot;
  $plot->setFunction($_POST['strFunc']);
  $plot->setBeetweenX($_POST['betweenX_1'], $_POST['betweenX_2']);
  $plot->setBeetweenY($_POST['betweenY_1'], $_POST['betweenY_2']);
  $wa->doIt($plot);
  $plot->setResponseHandler(new WolframAlpha_Response_Xml);
  echo $plot->getResponseHandler()->getJson();
}
 
Последнее редактирование:

stalxed

Новичок
По ООП считаю для новичков книга номер 1 - это Крэг Ларман:
http://www.ozon.ru/context/detail/id/3105480/

Коментарий по этой книге Фаулера(в конце книги patterns of enterprise application architecture):
Larman. Applying UML and Patterns, Second Edition. Prentice Hall, 2001.
Currently my first-choice introduction to OO design.
 
Сверху