search
HomeBackend DevelopmentPHP TutorialExtending OctoberCMS - Building a Soft-Delete Plugin

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!

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();
    }
}

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

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);
        });
    });
});

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.

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();
    }
}

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.

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);
        });
    });
});
php artisan create:plugin rafie.blogplus

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).

# updates/version.yaml

1.0.1:
    - First version of blogplus.
    - create_posts_deleted_at_field.php

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.

# 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');
        });
    }
}

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.

// 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',
        ],
    ]);
});

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.

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();
    }
}

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

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);
        });
    });
});
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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor