Home >Backend Development >PHP Tutorial >Extending OctoberCMS - Building a Soft-Delete Plugin

Extending OctoberCMS - Building a Soft-Delete Plugin

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-10 10:21:14966browse

Extending OctoberCMS - Building a Soft-Delete Plugin

OctoberCMS: In-depth exploration of plug-in extensibility and practical software removal of plug-in

Developers generally prefer easy-to-use and scalable CMS. OctoberCMS adheres to the concept of simplicity first, bringing a pleasant experience to developers and users. This article demonstrates some of the extensible features of OctoberCMS and extends the functionality of another plug-in with a simple plug-in.

Extending OctoberCMS - Building a Soft-Delete Plugin

Key Points

  • OctoberCMS provides a simple and easy-to-use CMS while allowing extensions through plug-ins. This scalability is reflected in the extent to which developers can penetrate the internal mechanisms of CMS, including modifying the functions of other developers plug-ins.
  • The Rainlab Blog plugin allows you to create articles and assign them to different categories. This tutorial demonstrates how to extend this plugin, add soft delete features, preventing articles from being permanently deleted, but instead mark them as "deleted" and record timestamps.
  • To create a soft delete feature, you need to create a new plug-in and add a deleted_at field to the database. This field will save the timestamp for the article deletion. The plugin then extends the article list to include this new field as a column and adds a filter to show or hide deleted articles.
  • The last step in creating a soft delete function is to intercept the article's deletion operation and update the deleted_at column. This is done by attaching to the deleting event triggered by Eloquent, preventing the deletion of records. Instead, the deleted_at field will be updated to the current timestamp and the record will be saved.

Introduction

Each CMS has a plug-in system to extend the functionality of the platform, and we measure its scalability by the extent to which we can penetrate the internal mechanisms of the CMS. However, we are talking about not only the CMS itself, but also the plug-ins!

If you build a plugin, you need to make sure other developers can modify some of your features. For example, we have a blog plugin where users can publish articles by selecting articles in the list. It is best to trigger an event to indicate that a new article has been published, another developer can mount to this event and notify subscribers via email!

<code class="language-php">class Posts extends Controller
{
    public function index_onPublish()
    {
        if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {

            foreach ($checkedIds as $postId) {
                if ((!$post = Post::find($postId)) || !$post->canEdit($this->user))
                    continue;

                $post->publish();
                Event::fire('rainlab.blog.posts.published', [$post]);
            }

            Flash::success('Successfully published those posts.');
        }

        return $this->listRefresh();
    }
}</code>

Other developers can listen to this event to handle published articles.

<code class="language-php">Event::listen('rainlab.blog.posts.published', function($post) {
    User::subscribedTo($post)->each(function($user) use($post) {
        Mail::send('emails.notifications.post-published', ['user' => $user, 'post' => $post], function($message) use($user, $post) {
            $message->from('us@example.com', 'New post by ' . $user->name);

            $message->to($user->email);
        });
    });
});</code>

We will mainly use events to hook to different parts of the request cycle. Let's start with a concrete example to better understand.

Rainlab Blog Plugin

If you have used OctoberCMS for a while, you must know about the Rainlab Blog plugin. It allows you to add articles in the backend and attach them to categories, and you can use components to display them in the frontend.

On the article list page, we can delete the article. But what if we want to softly delete them? Let's see if we can do this and learn more about OctoberCMS scalability.

Create a new plug-in

Create a new plugin for our demo using the scaffolding assistant command and update the plugin details in the Plugin.php file.

<code class="language-php">class Posts extends Controller
{
    public function index_onPublish()
    {
        if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {

            foreach ($checkedIds as $postId) {
                if ((!$post = Post::find($postId)) || !$post->canEdit($this->user))
                    continue;

                $post->publish();
                Event::fire('rainlab.blog.posts.published', [$post]);
            }

            Flash::success('Successfully published those posts.');
        }

        return $this->listRefresh();
    }
}</code>

Extended database mode

When talking about soft deletion, the first thing that comes to mind is the deleted_at field column that needs to exist in the database.

Create a new file named blogplus/updates under the create_posts_deleted_at_field.php folder and update the version.yaml file.

<code class="language-php">Event::listen('rainlab.blog.posts.published', function($post) {
    User::subscribedTo($post)->each(function($user) use($post) {
        Mail::send('emails.notifications.post-published', ['user' => $user, 'post' => $post], function($message) use($user, $post) {
            $message->from('us@example.com', 'New post by ' . $user->name);

            $message->to($user->email);
        });
    });
});</code>
<code class="language-bash">php artisan create:plugin rafie.blogplus</code>

Migrate the class changes the rainlab_blog_posts table and adds our deleted_at column, which defaults to null. Don't forget to run the php artisan plugin:refresh rafie.blogplus command to make the changes take effect.

Extended Article List

Next we have to add our fields as columns to the list for display. OctoberCMS provides us with an event to mount and change the currently displayed widget (the backend list is considered a widget).

<code class="language-yaml"># updates/version.yaml

1.0.1:
    - First version of blogplus.
    - create_posts_deleted_at_field.php</code>

Note: The above code should be placed in the Plugin@boot method.

We have an if statement to prevent our code from executing on each page, and then we add a new column to the list widget, and we can also use the removeColumn method to delete any existing columns. Check the documentation for a list of available column options.

Extending OctoberCMS - Building a Soft-Delete Plugin

Extended Filter

The column at the top of the article list allows users to filter lists using dates, categories, etc. In our case, we need a filter to show/hide deleted articles.

<code class="language-php"># updates/create_posts_deleted_at_field.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsDeletedAtField extends Migration
{
    public function up()
    {
        Schema::table('rainlab_blog_posts', function (Blueprint $table) {
            $table->timestamp('deleted_at')->nullable()->default(null);
        });
    }

    public function down()
    {
        Schema::table('rainlab_blog_posts', function (Blueprint $table) {
            $table->dropColumn('deleted_at');
        });
    }
}</code>

You can read more about list filters in the documentation. The above code is quite simple and contains only a few options. However, the scope attribute should be the name of the query scope method defined in the Models\Post model instance.

Extensible Class

OctoberRainExtensionExtendableTrait trait provides a magic method to dynamically extend existing classes by adding new methods, attributes, behaviors, etc. In our example, we need to add a new method to the article model to handle our scope filter.

<code class="language-php">// plugin.php  在Plugin类的boot方法中

Event::listen('backend.list.extendColumns', function ($widget) {
    if (!($widget->getController() instanceof \Rainlab\Blog\Controllers\Posts)) {
        return;
    }

    $widget->addColumns([
        'deleted_at' => [
            'label' => 'Deleted',
            'type' => 'date',
        ],
    ]);
});</code>

We can do the same for addDynamicProperty, asExtension, etc. Let's refresh our article list to see if our changes work.

Extending OctoberCMS - Building a Soft-Delete Plugin Extending OctoberCMS - Building a Soft-Delete Plugin

Of course, we don't have any deleted articles yet, because we need to complete the last part: intercepting the deletion operation of the article, and only updating the deleted_at column.

Tip: Instead of using the scope property, you can use the conditions to specify a simple where condition. The following code works the same as using the model scope.

<code class="language-php">class Posts extends Controller
{
    public function index_onPublish()
    {
        if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {

            foreach ($checkedIds as $postId) {
                if ((!$post = Post::find($postId)) || !$post->canEdit($this->user))
                    continue;

                $post->publish();
                Event::fire('rainlab.blog.posts.published', [$post]);
            }

            Flash::success('Successfully published those posts.');
        }

        return $this->listRefresh();
    }
}</code>

Eloquent Event

Eloquent triggers a series of events on each operation (create, update, delete, etc.). In this case, we need to hook to the delete event and prevent the deletion of the record.

When deleting a record, the

event is triggered before the actual deletion operation is performed, and the deleting event is triggered afterward. If you return false in the deleted event, the operation will abort. deleting

<code class="language-php">Event::listen('rainlab.blog.posts.published', function($post) {
    User::subscribedTo($post)->each(function($user) use($post) {
        Mail::send('emails.notifications.post-published', ['user' => $user, 'post' => $post], function($message) use($user, $post) {
            $message->from('us@example.com', 'New post by ' . $user->name);

            $message->to($user->email);
        });
    });
});</code>
Now we are ready to test the final result! Continue to delete some records, then go to the article list page to see if you can switch deleted items in the list.

Conclusion

This article provides a quick overview of how to extend the different parts of the OctoberCMS platform. You can read more about it in the extension plugin section of the documentation. If you have any questions or comments, please leave a message below!

FAQs about extending OctoberCMS and building soft delete plugins

What is the purpose of the software removal plug-in in OctoberCMS?

The soft delete plug-in in OctoberCMS is designed to prevent permanent data loss. When you delete a record, it is not completely deleted from the database. Instead, a

timestamp is set for the record. This means that from the application's point of view, the record is considered "deleted", but it can still be retrieved if needed. This is especially useful in scenarios where data may be deleted accidentally, as it allows for easy recovery. deleted_at

How is the difference between soft deletion and hard deletion?

Hard deletion permanently deletes records from the database and cannot be restored unless you have a backup. On the other hand, soft deletion simply marks the record as deleted and does not actually delete it from the database. This allows you to recover records if needed.

How to implement soft delete function in OctoberCMS?

To implement soft delete function in OctoberCMS, you need to create a plug-in. This includes creating a new plugin, adding

columns to the database table, and updating your model to use deleted_at trait. You can then use the SoftDeletes method on the model to softly delete the record and use the delete method to recover it. restore

How to test the soft delete function in OctoberCMS?

You can test the soft delete function by creating unit tests. This includes creating a new test case, creating a new record in the database, softly deleting it, and then asserting that it still exists in the database, but is marked as deleted.

Can I use the soft delete function with existing records?

Yes, you can use the soft delete function with existing records. You just need to add the

column to the existing database table. This column for all existing records will have a deleted_at value indicating that they have not been deleted. null

How to recover soft deleted records in OctoberCMS?

To recover soft deleted records, you can use the restore method on the model. This will remove the deleted_at timestamp from the record, effectively "undelete" it.

Can I permanently delete soft deleted records in OctoberCMS?

Yes, you can permanently delete soft deleted records using the forceDelete method on the model. This will delete records from the database like a hard deletion.

How to view all records, including soft deleted records in OctoberCMS?

To view all records, including soft deleted records, you can use the withTrashed method on the model. This will return all records, whether they have been soft deleted or not.

Can I customize the name of the deleted_at column in OctoberCMS?

Yes, you can customize the name of the getDeletedAtColumn column by overwriting the deleted_at method in the model. If deleted_at is not suitable for your needs, this allows you to use different column names.

Can I disable soft delete function for certain records in OctoberCMS?

Yes, you can disable soft delete for some records using the withoutGlobalScope method on the model. This allows you to exclude certain records from the soft delete feature.

The above is the detailed content of Extending OctoberCMS - Building a Soft-Delete Plugin. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn