Home >Backend Development >PHP Tutorial >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.
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. 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. 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.
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 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>
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.
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.
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.
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.
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 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
FAQs about extending OctoberCMS and building soft delete plugins
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 to implement soft delete function in OctoberCMS?
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
Can I use the soft delete function with existing records?
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
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.
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.
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.
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.
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!