Skip to content

Commit

Permalink
#1 Сделал контроллер ждя PurchaseStatuse
Browse files Browse the repository at this point in the history
  • Loading branch information
Goros6 committed Nov 20, 2014
1 parent 66b8d44 commit 4548b12
Show file tree
Hide file tree
Showing 6 changed files with 155 additions and 5 deletions.
7 changes: 4 additions & 3 deletions app/config/examples/database.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => '',
'username' => '',
'password' => '',
'database' => 'purchases',
'username' => 'homestead',
'password' => 'secret',
'charset' => 'utf8',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
Expand Down
2 changes: 1 addition & 1 deletion app/config/session.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
|
*/

'driver' => 'database',
'driver' => 'file',

/*
|--------------------------------------------------------------------------
Expand Down
137 changes: 137 additions & 0 deletions app/controllers/api/PurchaseStatusController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?php
namespace Goros6\Purchases\Controllers\Api;
use Controller;
use Goros6\Purchases\Models\PurchaseStatus;
use Input;
use Response;
use Exception;


class PurchaseStatusController extends Controller {

/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
try{
$statusCode = 200;
$response = [
'PurchaseStatuses' => []
];

$purSt = PurchaseStatus::all();

foreach($purSt as $pS){

$response['PurchaseStatuses'][] = [
'id' => $pS->id,
'name' => $pS->name
];
}

}catch (Exception $e){
$statusCode = 400;
}finally{
var_dump($response);
return Response::json($response, $statusCode);
}

This comment has been minimized.

Copy link
@mikanoz

mikanoz Nov 21, 2014

В данном случае ошибок быть не может (если будет отсутствовать модель или база данных, это не ошибка - это просто не рабочее приложение). Поэтому все делаем значительно проще. Как то так:

return [
    'PurchaseStatuses' => PurchaseStatus::all()->toArray(),
];

Будет автоматически создан ответ в JSON-формате с кодом 200.

}


/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}


/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
$input = Input::all();
var_dump($input);
$purSt = new PurchaseStatus();
$purSt->name = $input['name'];
$purSt->save();
}

This comment has been minimized.

Copy link
@mikanoz

mikanoz Nov 21, 2014

После успешного сохранения, хорошо бы выдать результат сохранения. Обычно делают в том же формате, что и получение данных одной модели. Т.к. получение данных одной модели уже есть, можно после сохранения сделать:

return $this->show($purSt->id);

Т.е. формат ответа на создание и на получение информации о модели будет одинаковый.



/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
try{
$purSt = PurchaseStatus::find($id);
$statusCode = 200;
$response = [
'PurchaseStatuses' => ['id' => $purSt->id,
'name' => $purSt->name
]];
}catch (Exception $e){
$statusCode = 400;
$response = [
"error" => "Status doesn`t exists"
];
}finally{
var_dump($response);
return Response::json($response, $statusCode);
}
}

This comment has been minimized.

Copy link
@mikanoz

mikanoz Nov 21, 2014

Замечание аналогичное первому. Проверки по сути лишние. Можно сделать так:

$purSt = PurchaseStatus::findOrFail($id); // бросит исключение ModelNotFoundException, если по id записи не будет
return [
    'PurchaseStatus' => $purSt->toArray(),
];

И этого будет достаточно. Клиент автоматически получит код http, отличный от 200, если данных в базе по этому $id нет, а других ошибок здесь просто никогда не возникнет.



/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}


/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}


/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}


}
3 changes: 3 additions & 0 deletions app/models/PurchaseStatus.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
* Date: 06.11.2014
* Time: 1:07
*/
namespace Goros6\Purchases\Models;
use Eloquent;

class PurchaseStatus extends Eloquent
{
public $timestamps = false;
Expand Down
5 changes: 5 additions & 0 deletions app/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@
{
return View::make('hello');
});

Route::group(array('prefix' => 'v1/api'), function() {
Route::resource('purchaseStatus', 'Goros6\\Purchases\\Controllers\\Api\\PurchaseStatusController');
});

6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
],
"psr-4":{
"Goros6\\Purchases\\Controllers\\api\\": "app/controllers/api",
"Goros6\\Purchases\\Models\\": "app/models"
}
},
"scripts": {
"post-install-cmd": [
Expand Down

0 comments on commit 4548b12

Please sign in to comment.