国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Key Points
Introduction
Rainlab Blog Plugin
Create a new plug-in
Extended database mode
Extended Article List
Extended Filter
Extensible Class
Eloquent Event
How to recover soft deleted records in OctoberCMS?
Can I permanently delete soft deleted records in OctoberCMS?
How to view all records, including soft deleted records in OctoberCMS?
Can I customize the name of the deleted_at column in OctoberCMS?
Can I disable soft delete function for certain records in OctoberCMS?
Home Backend Development PHP Tutorial Extending OctoberCMS - Building a Soft-Delete Plugin

Extending OctoberCMS - Building a Soft-Delete Plugin

Feb 10, 2025 am 10:21 AM

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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are some best practices for versioning a PHP-based API? What are some best practices for versioning a PHP-based API? Jun 14, 2025 am 12:27 AM

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

What are weak references (WeakMap) in PHP, and when might they be useful? What are weak references (WeakMap) in PHP, and when might they be useful? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

What are the differences between procedural and object-oriented programming paradigms in PHP? What are the differences between procedural and object-oriented programming paradigms in PHP? Jun 14, 2025 am 12:25 AM

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

See all articles