post crud

This commit is contained in:
Билай Станислав 2024-07-25 16:15:18 +03:00
parent 653bf674c9
commit 25e585655c
16 changed files with 303 additions and 46 deletions

View File

@ -4,21 +4,103 @@ namespace app\controllers;
use app\helpers\Debug;
use app\models\forms\CreatePostForm;
use app\models\Post;
use app\models\User;
use app\services\PostService;
use app\services\UserService;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\Controller;
class PostController
class PostController extends Controller
{
public function actionCreatePost($post, $user_id)
protected function init(): void
{
return Post::create(['post'=>$post, 'user_id'=>$user_id]);
$this->cgView->viewPath = ROOT_DIR . "/views/admin/";
$this->cgView->layout = "layouts/main.php";
}
public function actionCreate(): void
{
$this->cgView->render("post/form.php");
}
#[NoReturn] public function actionAdd(): void
{
$postForm = new CreatePostForm();
$postService = new PostService();
$postForm->load($_REQUEST);
if((new UserService)->check($_REQUEST['username'])) {
if ($postForm->validate()) {
$post = $postService->create($postForm);
if ($post) {
$this->redirect("/admin/post/" . $post->id);
}
}
}
$this->redirect("/admin/post/create");
}
/**
* @throws Exception
*/
public function actionIndex(): void
{
Debug::dd("Post list");
foreach (Post::all() as $post)
{
echo $post->post . "<br>";
$posts = Post::all();
$this->cgView->render("post/index.php", ['posts' => $posts]);
}
/**
* @throws Exception
*/
public function actionView($id): void
{
$post = Post::find($id);
if (!$post){
throw new Exception(message: "The post not found");
}
$this->cgView->render("post/view.php", ['post' => $post]);
}
/**
* @throws Exception
*/
public function actionUpdate($id): void
{
$model = Post::find($id);
if (!$model){
throw new Exception(message: "The post not found");
}
$this->cgView->render("post/form.php", ['model' => $model]);
}
public function actionEdit($id): void
{
$post = Post::find($id);
if (!$post){
throw new Exception(message: "The user not found");
}
$postForm = new CreatePostForm();
$postService = new PostService();
$postForm->load($_REQUEST);
if((new UserService)->check($_REQUEST['username'])) {
if ($postForm->validate()) {
$post = $postService->update($postForm, $post);
if ($post) {
$this->redirect("/admin/post/" . $post->id);
}
}
}
$this->redirect("/admin/post/update/" . $id);
}
#[NoReturn] public function actionDelete($id): void
{
Post::find($id)->delete();
$this->redirect("/admin/post/");
}
}

View File

@ -50,8 +50,6 @@ class UserController extends Controller{
$this->redirect("/admin/user/create");
}
public function actionQuestionCount($user_id)
{
return Question::where('user_id', $user_id)->count();
@ -62,7 +60,8 @@ class UserController extends Controller{
*/
public function actionIndex(): void
{
$users = User::where(['role' => 1])->get();
// $users = User::where(['role' => 1])->get();
$users = User::all();
$this->cgView->render("user/index.php", ['users' => $users]);
}
@ -77,20 +76,6 @@ class UserController extends Controller{
if (!$user){
throw new Exception(message: "The user not found");
}
// $this->twig->addFunction(new TwigFunction('table', function () use ($user){
// $dataProvider = new ViewJsonTableEloquentModel($user, [
// 'params' => ["class" => "table table-bordered", "border" => "2"],
// 'baseUrl' => "/admin/user",
// ]);
// $table = new ViewJsonTable($dataProvider->getJson());
// $table->beforeTable(function (){
// return PrimaryBtn::create("Список", "/admin/user")->fetch();
// });
// $table->create();
// $table->render();
// }));
//
// echo $this->twig->render('user_table.html.twig');
$this->cgView->render("user/view.php", ['user' => $user]);
}
@ -134,7 +119,6 @@ class UserController extends Controller{
{
User::find($id)->delete();
$this->redirect("/admin/user/");
}
}

View File

@ -2,8 +2,26 @@
namespace app\models;
use \Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $post
* @property string $username
* @method static where(int[] $array)
* @method static find($id)
*/
class Post extends Model
{
protected $table = 'post';
protected $fillable = ['post', 'user_id'];
protected $fillable = ['post', 'username'];
public static function labels(): array
{
return [
'post' => 'Пост',
'username' => 'Пользователь',
'created_at' => 'Создан',
'updated_at' => 'Обновлен'
];
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace app\models\forms;
use kernel\FormModel;
class CreatePostForm extends FormModel
{
public function rules(): array
{
return [
'post' => 'required|min-str-len:1|max-str-len:2048',
'username' => 'required|min-str-len:1|max-str-len:50',
];
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace app\services;
use app\models\Post;
use kernel\FormModel;
class PostService
{
public function create(FormModel $form_model): false|Post
{
$model = new Post();
$model->post = $form_model->getItem('post');
$model->username = $form_model->getItem('username');
if ($model->save()){
return $model;
}
return false;
}
public function update(FormModel $form_model, Post $post): false|Post
{
$post->post = $form_model->getItem('post');
$post->username = $form_model->getItem('username');
if ($post->save()){
return $post;
}
return false;
}
}

View File

@ -2,6 +2,7 @@
namespace app\services;
use app\helpers\Debug;
use app\models\User;
use kernel\FormModel;
@ -33,4 +34,13 @@ class UserService
return false;
}
public function check(string $username): bool
{
if (User::where(['username' => $username])->first())
{
return true;
}
return false;
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace app\tables\columns;
use Itguild\Tables\ActionColumn\ActionColumn;
class UserDeleteActionColumn extends ActionColumn
{
protected string $prefix = "/";
public function fetch(): string
{
// $link = $this->baseUrl . $this->prefix . $this->id . $this->prefix . "update";
$link = $this->baseUrl . $this->prefix . "delete" . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-danger'>Удалить</a> ";
}
}

View File

@ -12,6 +12,6 @@ class UserEditActionColumn extends ActionColumn
{
// $link = $this->baseUrl . $this->prefix . $this->id . $this->prefix . "update";
$link = $this->baseUrl . $this->prefix . "update" . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-primary'>Редактировать</a> ";
return " <a href='$link' class='btn btn-success'>Редактировать</a> ";
}
}

View File

@ -23,30 +23,21 @@ $router->group(["prefix" => "admin"], function (RouteCollector $router){
$router->get('/create', [\app\controllers\UserController::class, 'actionCreate']);
$router->post("/", [\app\controllers\UserController::class, 'actionAdd']);
$router->get('/{id}', [\app\controllers\UserController::class, 'actionView']);
// $router->get('/{id}/update', [\app\controllers\UserController::class, 'actionUpdate']);
$router->any('/update/{id}', [\app\controllers\UserController::class, 'actionUpdate']);
$router->any("/edit/{id}", [\app\controllers\UserController::class, 'actionEdit']);
$router->get('/delete/{id}', [\app\controllers\UserController::class, 'actionDelete']);
});
$router->group(["prefix" => "question"], function (RouteCollector $router){
$router->get('/create', [QuestionController::class, 'actionCreate']);
$router->get('/update', [QuestionController::class, 'actionUpdate']);
$router->get('/delete/{id}', [QuestionController::class, 'actionDelete']);
$router->get('/', [QuestionController::class, 'actionIndex']);
$router->get('/{id}', [QuestionController::class, 'actionView']);
$router->post("/", [QuestionController::class, 'actionAdd']);
$router->post("/edit", [QuestionController::class, 'actionEdit']);
});
$router->group(["prefix" => "post"], function (RouteCollector $router){
$router->get('/', [\app\controllers\PostController::class, 'actionIndex']);
$router->get('/create', [\app\controllers\PostController::class, 'actionCreate']);
$router->post("/", [\app\controllers\PostController::class, 'actionAdd']);
$router->get('/{id}', [\app\controllers\PostController::class, 'actionView']);
$router->any('/update/{id}', [\app\controllers\PostController::class, 'actionUpdate']);
$router->any("/edit/{id}", [\app\controllers\PostController::class, 'actionEdit']);
$router->get('/delete/{id}', [\app\controllers\PostController::class, 'actionDelete']);
});
});
$router->get('/allQuestions', [QuestionController::class, 'actionViewAllQuestions']);
$router->get('/allAnswers', [AnswerController::class, 'actionViewAllAnswers']);
$dispatcher = new Phroute\Phroute\Dispatcher($router->getData());
$response = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

2
m.php
View File

@ -9,6 +9,6 @@ require_once __DIR__ . "/vendor/autoload.php";
require_once __DIR__ . "/bootstrap.php";
//UserMigration::up();
//PostMigration::up();
PostMigration::up();
//AnswerMigration::up();
//QuestionMigration::up();

View File

@ -18,8 +18,8 @@ class PostMigration extends Migration
{
Manager::schema()->create('post', function (Blueprint $table) {
$table->increments('id');
$table->string('post', 255)->nullable(false);
$table->integer('user_id');
$table->string('post', 3000)->nullable(false);
$table->string('username', 255)->nullable(false);
$table->timestamps();
});
}

51
views/admin/post/form.php Normal file
View File

@ -0,0 +1,51 @@
<?php
/**
* @var Post $model
*/
use app\models\Post;
$form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/post/edit/" . $model->id : "/admin/post");
$form->field(class: \itguild\forms\inputs\TextArea::class, name: "post", params: [
'class' => "form-control",
'placeholder' => 'Пост',
'rows' => '10',
'value' => $model->post ?? ''
])
->setLabel("Пост")
->render();
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "username", params: [
'class' => "form-control",
'placeholder' => 'Логин',
'value' => $model->username ?? ''
])
->setLabel("Имя пользователя")
->render();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,30 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $posts
*/
use app\models\Post;
use app\tables\columns\UserDeleteActionColumn;
use app\tables\columns\UserEditActionColumn;
use app\tables\columns\UserViewActionColumn;
use Itguild\Tables\ListJsonTable;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\ListJsonTableEloquentCollection;
$dataProvider = new ListJsonTableEloquentCollection($posts, [
'model' => Post::class,
'perPage' => 5,
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/post",
]);
$table = new ListJsonTable($dataProvider->getJson());
$table->beforePrint(function (){
return PrimaryBtn::create("Создать", "/admin/post/create")->fetch();
//return (new PrimaryBtn("Создать", "/admin/user/create"))->fetch();
});
$table->addAction(UserViewActionColumn::class);
$table->addAction(UserEditActionColumn::class);
$table->addAction(UserDeleteActionColumn::class);
$table->create();
$table->render();

24
views/admin/post/view.php Normal file
View File

@ -0,0 +1,24 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $post
*/
use Itguild\Tables\ViewJsonTable;
use kernel\IGTabel\btn\DangerBtn;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\btn\SuccessBtn;
use kernel\IGTabel\ViewJsonTableEloquentModel;
$dataProvider = new ViewJsonTableEloquentModel($post, [
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/user",
]);
$table = new ViewJsonTable($dataProvider->getJson());
$table->beforeTable(function () use ($post) {
$btn = PrimaryBtn::create("Список", "/admin/post")->fetch();
$btn .= SuccessBtn::create("Редактировать", "/admin/post/update/" . $post->id)->fetch();
$btn .= DangerBtn::create("Удалить", "/admin/post/delete/" . $post->id)->fetch();
return $btn;
});
$table->create();
$table->render();

View File

@ -11,7 +11,7 @@ $form->beginForm(isset($model) ? "/admin/user/edit/" . $model->id : "/admin/user
$form->field(class: \itguild\forms\inputs\TextInput::class, name: "username", params: [
'class' => "form-control",
'placeholder' => 'Логин',
'model' => $model->username ?? ''
'value' => $model->username ?? ''
])
->setLabel("Логин")
->render();

View File

@ -5,6 +5,7 @@
*/
use app\models\User;
use app\tables\columns\UserDeleteActionColumn;
use app\tables\columns\UserEditActionColumn;
use app\tables\columns\UserViewActionColumn;
use Itguild\Tables\ListJsonTable;
@ -24,5 +25,6 @@ $table->beforePrint(function (){
});
$table->addAction(UserViewActionColumn::class);
$table->addAction(UserEditActionColumn::class);
$table->addAction(UserDeleteActionColumn::class);
$table->create();
$table->render();