Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

php - Making controller thinner. Laravel 8

I have PostController, here is its method store().

public function store(Request $request)
{
    $this->handleUploadedImage(
        $request->file('upload'),
        $request->input('CKEditorFuncNum')
    );

    $post = Post::create([
        'content'      => request('content'),
        'is_published' => request('is_published'),
        'slug'         => Carbon::now()->format('Y-m-d-His'),
        'title'        => $this->firstSentence(request('content')),
        'template'     => $this->randomTemplate(request('template')),
    ]);
    $post->tag(explode(',', $request->tags));

    return redirect()->route('posts');
}

Method handleUploadedImage() now stored in PostController itself. But I'm going to use it in other controllers. Where should I move it? Not in Request class, because it's not about validation. Not in Models/Post, because it's not only for Post model. And it's not so global function for Service Provider class.

Methods firstSentence() and randomTemplate() are stored in that controller too. They will only be used in it. Maybe I should move them in Models/Post? In that way, how exactly call them in method store() (more specifically, in method create())?

I read the theory, and I understand (hopefully) the Concept of Thin Controllers and Fat Models, but I need some practical concrete advice with this example. Could you please suggest, where to move and how to call these methods?

question from:https://stackoverflow.com/questions/65849520/making-controller-thinner-laravel-8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, a note: I don't work with Laravel, so I'll show you a general solution, pertinent to all frameworks.

Indeed, the controllers should always be kept thin. But this should be appliable to the model layer as well. Both goals are achievable by moving application-specific logic into application services (so, not into the model layer, making the models fat!). They are the components of the so-called service layer. Read this as well.

In your case, it seems that you can elegantly push the handling logic for uploaded images into a service, like AppServiceHttpUploadImageHandler, for example, containing a handle method. The names of the class and method could be chosen better, though, dependent on the exact class responsibility.

The logic for creating and storing a post would go into another application service: AppServicePost, for example. In principle, this service would perform the following tasks:

  1. Create an entity - DomainModelPostPost, for example - and set its properties (title, content, is_published, template, etc) based on the user input. This could be done in a method AppServicePost::createPost, for example.
  2. Store the entity in the database, as a database record. This could be done in a method AppServicePost::storePost, for example.
  3. Other tasks...

In regard of the first task, two methods of the AppServicePost service could be useful:

  • generatePostTitle, encapsulating the logic of extracting the first sentence from the user-provided "content", in order to set the title of the post entity from it;
  • generatePostTemplate, containing the logic described by you in the comment in regard of randomTemplate().

In regard of the second task, personally, I would store the entity in the database by using a specific data mapper - to directly communicate with the database API - and a specific repository on top of it - as abstraction of a collection of post objects.

Service:

<?php

namespace AppService;

use Carbon;
use DomainModelPostPost;
use DomainModelPostPostCollection;

/**
 * Post service.
 */
class Post {

    /**
     * Post collection.
     * 
     * @var PostCollection
     */
    private $postCollection;

    /**
     * @param PostCollection $postCollection Post collection.
     */
    public function __construct(PostCollection $postCollection) {
        $this->postCollection = $postCollection;
    }

    /**
     * Create a post.
     * 
     * @param string $content Post content.
     * @param string $template The template used for the post.
     * @param bool $isPublished (optional) Indicate if the post is published.
     * @return Post Post.
     */
    public function createPost(
        string $content,
        string $template,
        bool $isPublished
        /* , ... */
    ) {
        $title = $this->generatePostTitle($content);
        $slug = $this->generatePostSlug();
        $template = $this->generatePostTemplate($template);

        $post = new Post();

        $post
            ->setTitle($title)
            ->setContent($content)
            ->setIsPublished($isPublished ? 1 : 0)
            ->setSlug($slug)
            ->setTemplate($template)
        ;

        return $post;
    }

    /**
     * Store a post.
     * 
     * @param Post $post Post.
     * @return Post Post.
     */
    public function storePost(Post $post) {
        return $this->postCollection->storePost($post);
    }

    /**
     * Generate the title of a post by extracting 
     * a certain part from the given post content.
     * 
     * @return string Generated post title.
     */
    private function generatePostTitle(string $content) {
        return substr($content, 0, 300) . '...';
    }

    /**
     * Generate the slug of a post.
     * 
     * @return string Generated slug.
     */
    private function generatePostSlug() {
        return Carbon::now()->format('Y-m-d-His');
    }

    /**
     * Generate the template assignable to 
     * a post based on the given template.
     * 
     * @return string Generated post template.
     */
    private function generatePostTemplate(string $template) {
        return 'the-generated-template';
    }

}

Repository interface:

<?php

namespace DomainModelPost;

use DomainModelPostPost;

/**
 * Post collection interface.
 */
interface PostCollection {

    /**
     * Store a post.
     * 
     * @param Post $post Post.
     * @return Post Post.
     */
    public function storePost(Post $post);

    /**
     * Find a post by id.
     * 
     * @param int $id Post id.
     * @return Post|null Post.
     */
    public function findPostById(int $id);

    /**
     * Find all posts.
     * 
     * @return Post[] Post list.
     */
    public function findAllPosts();

    /**
     * Check if the given post exists.
     * 
     * @param Post $post Post.
     * @return bool True if post exists, false otherwise.
     */
    public function postExists(Post $post);
}

Repository implementation:

<?php

namespace DomainInfrastructureRepositoryPost;

use DomainModelPostPost;
use DomainInfrastructureMapperPostPostMapper;
use DomainModelPostPostCollection as PostCollectionInterface;

/**
 * Post collection.
 */
class PostCollection implements PostCollectionInterface {

    /**
     * Posts list.
     * 
     * @var Post[]
     */
    private $posts;

    /**
     * Post mapper.
     * 
     * @var PostMapper
     */
    private $postMapper;

    /**
     * @param PostMapper $postMapper Post mapper.
     */
    public function __construct(PostMapper $postMapper) {
        $this->postMapper = $postMapper;
    }

    /**
     * Store a post.
     * 
     * @param Post $post Post.
     * @return Post Post.
     */
    public function storePost(Post $post) {
        $savedPost = $this->postMapper->savePost($post);

        $this->posts[$savedPost->getId()] = $savedPost;

        return $savedPost;
    }

    /**
     * Find a post by id.
     * 
     * @param int $id Post id.
     * @return Post|null Post.
     */
    public function findPostById(int $id) {
        //... 
    }

    /**
     * Find all posts.
     * 
     * @return Post[] Post list.
     */
    public function findAllPosts() {
        //...
    }

    /**
     * Check if the given post exists.
     * 
     * @param Post $post Post.
     * @return bool True if post exists, false otherwise.
     */
    public function postExists(Post $post) {
        //...
    }

}

Data mapper interface:

<?php

namespace DomainInfrastructureMapperPost;

use DomainModelPostPost;

/**
 * Post mapper.
 */
interface PostMapper {

    /**
     * Save a post.
     * 
     * @param Post $post Post.
     * @return Post Post entity with id automatically assigned upon persisting.
     */
    public function savePost(Post $post);

    /**
     * Fetch a post by id.
     * 
     * @param int $id Post id.
     * @return Post|null Post.
     */
    public function fetchPostById(int $id);

    /**
     * Fetch all posts.
     * 
     * @return Post[] Post list.
     */
    public function fetchAllPosts();

    /**
     * Check if a post exists.
     * 
     * @param Post $post Post.
     * @return bool True if the post exists, false otherwise.
     */
    public function postExists(Post $post);
}

Data mapper PDO implementation:

<?php

namespace DomainInfrastructureMapperPost;

use PDO;
use DomainModelPostPost;
use DomainInfrastructureMapperPostPostMapper;

/**
 * PDO post mapper.
 */
class PdoPostMapper implements PostMapper {

    /**
     * Database connection.
     * 
     * @var PDO
     */
    private $connection;

    /**
     * @param PDO $connection Database connection.
     */
    public function __construct(PDO $connection) {
        $this->connection = $connection;
    }

    /**
     * Save a post.
     * 
     * @param Post $post Post.
     * @return Post Post entity with id automatically assigned upon persisting.
     */
    public function savePost(Post $post) {
        /*
         * If $post->getId() is set, then call $this->updatePost() 
         * to update the existing post record in the database.
         * Otherwise call $this->insertPost() to insert a new 
         * post record in the database.
         */
        // ...
    }

    /**
     * Fetch a post by id.
     * 
     * @param int $id Post id.
     * @return Post|null Post.
     */
    public function fetchPostById(int $id) {
        //...    
    }

    /**
     * Fetch all posts.
     * 
     * @return Post[] Post list.
     */
    public function fetchAllPosts() {
        //...
    }

    /**
     * Check if a post exists.
     * 
     * @param Post $post Post.
     * @return bool True if the post exists, false otherwise.
     */
    public function postExists(Post $post) {
        //...
    }

    /**
     * Update an existing post.
     * 
     * @param Post $post Post.
     * @return Post Post entity with the same id upon updating.
     */
    private function updatePost(Post $post) {
        // Persist using SQL and PDO statements...
    }

    /**
     * Insert a post.
     * 
     * @param Post $post Post.
     * @return Post Post entity with id automatically assigned upon persisting.
     */
    private function insertPost(Post $post) {
        // Persist using SQL and PDO statements...
    }

}

In the end, your controller would look something like bellow. By reading its code, its role becomes obvious: just to push the user input to the service layer. The use of a service layer provides the big advantage of reusability.

<?php

namespace AppController;

use AppServicePost;
use AppServiceHttpUploadImageHandler;

class PostController {

    private $imageHandler;
    private $postService;

    public function __construct(ImageHandler $imageHandler, Post $postService) {
        $this->imageHandler = $imageHandler;
        $this->postService = $postService;
    }

    public function storePost(Request $request) {
        $this->imageHandler->handle(
            $request->file('upload'),
            $request->input('CKEditorFuncNum')
        );

        $post = $this->postService->createPost(
            request('content'),
            request('template'),
            request('is_published')
            /* , ... */
        );

        return redirect()->route('posts');
    }

}

PS: Keep in mind, that the model layer MUST NOT know anything about where its data is coming from, nor about how the data passed to it was created. So, the model layer must not know anything about a browser, or a


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...