When you develop with October CMS, one of the most effective tools available is incorporating models into custom components. October CMS is renowned for its versatility and user-friendliness, and incorporating models into your custom components can enhance its capabilities, making the developing process much more effective. Models included in October CMS offer a structured method to interface with your database and allow you to access, update, and manage your data quickly. Building dynamic websites based on data that provide a seamless user experience is crucial.
For developers participating in CMS Plugin Development October, knowing how to use models is crucial to maximizing how your customized components perform. Models let you define relationships between different data sets and execute complicated queries to ensure the app is robust and scalable. When you incorporate models into your components, they can drastically simplify your code and enhance the reliability of your application. This blog will discuss how you can use models efficiently within custom components, equipping you with the necessary information to improve the October CMS improvement to the next step.
Principal Benefits of Models in Custom Components
Utilizing Models inside custom components in October CMS offers significant advantages. It allows October CMS development company to access and control database information within their component, resulting in better code quality, enhanced data security, and increased flexibility when creating dynamic web-based features. All this is possible by leveraging the potential of Laravel’s Eloquent ORM, which is the foundation of the October CMS model framework.
Data Access and Manipulation
Models make it simple to create, query updates, delete, and create data records in your components. They remove the requirement to create simple SQL queries and ease data handling.
Object-Oriented Programming
Using Models, you can think of data in databases as objects, which allows for a cleaner and more intuitive code structure, with methods to manage relationships between different entities in the database.
Validation and Data Integrity
The October CMS Model system has built-in validation tools, allowing you to set the rules for entering data into your components. These tools ensure the accuracy of data and prevent entry errors.
Relationship Management
Models enable you to quickly create relationships between multiple database tables, allowing you to find relevant data within your component quickly.
Reusability
Once you’ve made the Model, you can apply it to different parts of your work, encouraging code reuse and consistency.
Component Logic Separation
Utilizing Models, you can cleanly separate your program’s presentation logic from the logic for data access, which improves the maintainability of your code.
Improved Development Speed
Utilizing models for October CMS is easy, drastically reducing the time required to design complicated components based on data.
Building CMS Components
Extension of the CMS by adding custom components.
Components directories and files reside in the subdirectory for components of the plugin directory. Each component contains a PHP file that defines the element’s class and an optional directory for partials of the element. The name of the component partials directory corresponds to the element’s class name, which is written in lowercase. An example of a part directory structure:
+– plugins
+– Acme
+– Blog
+– components
+– default.htm – Default Markup (Optional)
+– BlogPosts.php – Component Class
+– Plugin.php
Components must be added to the plugin registration file using registration methods such as registerComponents. Components are configured with properties and inspector definitions of type.
Take Your October CMS Site to The Next Level-Let’s Make It Happen!
Pooja Upadhyay
Director Of People Operations & Client Relations
Component Class Definition
The command to create: component will create a new class of component and the default view of the component. The first argument defines the name of the author and the plugin. In the second, you specify the class of the component name.
Php artisan creates component Acme.Blog BlogPosts
Component class files define the component’s features and properties. The class file name must match the class name. Component classes should extend the CmsClassesComponentBase class. The element from the following example should be defined in the plugins/acme/blog/components/BlogPosts.php file.
namespace Acme\Blog\Components;
class BlogPosts extends \Cms\Classes\ComponentBase
{
Public Function ComponentDetails()
{
Return
‘name’ => ‘Blog Posts,’
“description” = ‘Displays the blog’s posts. ‘,
‘icon’ => ‘icon-puzzle-piece’
];
}
/**
* posts become visible on the page as |*|•}
*/
Posts for public functions()
{
return to the original Post Return’ Second Post Return’, ‘Third Post Return’;
}
}
A component details method is mandatory. The process must produce an array with two keys: description and name. The description and name appear in the CMS back-end user interface.
When the component is added to a layout or page, the properties and methods are accessible on the page via the element variable whose name matches the short name of the element and the name of its alias. For instance, when the BlogPost component in this example has been inserted on a page, it would be displayed with its short title:
URL = “/blog”
[blogPosts]
==
You can access the method for postings via its blogPosts variable. Be aware that Twig uses the property notation of methods, which means you don’t need to use brackets.
|post}
*% end for %
Component Registration
Components must be registered using the registerComponents method in your plugin’s registration files. This informs CMS regarding the Component and gives it an abbreviated name to use. An example of how to register the component is:
public function RegisterComponents()
{
Return
\October\Demo\Components\Todo::class => ‘demoTodo’
];
}
This will enable the Todo component class to use the default name of demoTodo as an alias. Additional information about using components is available in this CMS component article.
Component Properties
If you add a component to the layout or page, you can set it up using properties. The properties are defined using the defineProperties method in the class. The following example demonstrates the technique of determining a property of a component by using a string inspector type.
public function defineProperties()
{
Return
‘maxItems’ => [
‘title’ => ‘Max items,’
“description” => “The largest number of items to be completed permitted’
‘default’ => 10,
‘type’ => ‘string’,
‘validation’ => [
‘regex’ => [
“message” => “The Max Items property can contain only numeric symbols. ‘,
‘pattern’ => ‘^[0-9]+$’
]
]
]
];
}
The method will result in an array with key property values as indexes and the parameter values for each property. These keys can be used to access the properties of the component inside the component’s class.
This inspector’s types section lists the property parameters and available types.
You can access the property’s value within the component using the properties method.
$this->property(‘maxItems’);
If the property’s value isn’t set, you can specify the default value in the second parameter of this property method.
$this->property(‘maxItems’, 6);
You could also download all properties as an array:
$properties = $this->getProperties();
To access the property using the component’s Twig partials, you can use the variable __SELF__, which refers to a component object.
Routing Parameters
Components can directly access the routing parameters specified within the URL.
/Returns the URL segment’s value, for example post_id: /page/
$postId = $this->param(‘post_id’);
In certain situations, component properties can act as an encoded value or refer to the value of the URL. This example of hardcoding illustrates the blog post using an identifier 2:
url = “/blog/hard-coded-page”
[blogPost]
ID = “2”
Alternatively, the value could be dynamically referenced from the page URL using the external value for a property within the component.
url = “/blog/:my_custom_parameter”
[blogPost]
ID is “}”
The value can be obtained in both cases by applying the property method.
$this->property(‘id’);
If you are required to access the name of the routing parameter
// Returns “my_custom_parameter”
$this->paramName(‘id’);
Handling the Page Execution Cycle
Components may be involved in the Page execution cycle by altering the one method of the class for components. The CMS controller runs this method each time the layout or page loads. In this method, you can add variables to the Twig environment using the property on a page:
public role onRun()
{
/The program will execute if the layout or page is
/loaded, and then the component is attached to it.
The $this->page’s ‘var’ = “value $this->page[‘var’] = ‘value’; // Add an element of the page with a variable
}
Page Execution Life Cycle Handlers
If a page loads, October performs handler functions that can be defined in the layout section, page PHP section, and component classes. The order in which handlers execute follows.
- Layout and OnInit() function.
- OnInit Page() function.
- Layout OnStart() Function.
- Layout components in the Run() method.
- Layout onBeforePageStart() function.
- page onStart() method.
- Page components using the Run() method.
- The Page OnEnd() function.
- Layout on End() function.
Component Initialization
There are times when you want to execute code while your component’s class is being created. You can modify the class’s init method to handle any initialization logic that will be executed prior to AJAX handlers and the page’s execution. For instance, this method is used to attach an additional element to the webpage dynamically.
public function()
{
$this->addComponent(\Acme\Blog\Components\BlogPosts::class, ‘blogPosts’);
}
Halting With a Response
Like every method in the Layout Execution Life Cycle, when the component’s run method returns a non-valid value, the process ends at this point and sends the response back to the user. This is where we send an access-denied message using the Response facade.
public function of Run()
{
If (true) {If (true)
return Response::make(‘Access denied! ‘, 403);
}
}
You may also get an error 404 from the onRun method.
public function of Run()
{
If (true) {If (true)
$this->setStatusCode(404);
return $this->controller->run(‘404’);
}
}
AJAX Handlers
Components may serve as hosts for AJAX events handlers. They are defined in the component class just as described in the layout or page code. A simple example AJAX handler method that is defined within a class of components:
public function on AddItem()
{
$value1 = post(‘value1’);
$value2 = post(‘value2’);
$this->page[‘result’] = $value1 + $value2;
}
If this component’s alias was demoTodo, this handler is accessible via demoTodo: onAddItem.
Default Markup
Each component can have standard markup, which is included when it is placed on a webpage using the % component% tag, though this isn’t required. The default markup is saved in the directory for partials of components that share identical names as a lower-case class.
The default component markup must be stored in a file called default.htm. For example, the default markup for the Demo ToDo component is defined in the file /plugins/october/demo/components/todo/default.htm. The component can be placed wherever on the page using the tag % component%:
url = “/todo”
[demoTodo]
The default markup could also include parameters that override the component’s properties when the markups are created.
These properties won’t be accessible using the on-run method because they are set after the cycle is completed. Instead, they can be handled through the override method on Render within the component class. The CMS controller implements this method before rendering the markup, which is the default.
public function of Render()
{
/ It will execute before the default component.
// Markup is displayed on the layout or page.
This->page[‘var’] = “Maximum items permitted: . $this->property(‘maxItems’);
}
Component Partials
As well as the markup that is the default, components may also provide additional partials to be used in the front end technology or within the markup that is the default. If the Demo ToDo component had a pagination partial, it would be located in /plugins/october/demo/components/todo/pagination.htm and displayed on the page using:
A flexible method may be employed, which is contextual. If a component is mentioned within a part, the name will use the term “self” to refer to it. If used within the theme’s partial, it will look through every component on the layout or page to find a partial name that matches and applies the name.
A partial ‘@pagination’
Multiple components can share partials by placing the partial file into the directory components/partials. The partials in this directory can be used as a backup if the typical component partial cannot be located. For example, a shared partial located in /plugins/acme/blog/components/partials/shared.htm can be displayed on the page by any element using:
A partial ‘@shared’
Referencing “self”
Components can reference themselves in their partials using the __SELF__ variables. By default, this will return the component’s short name or alias.
[…]
Components may also refer to the properties of their respective elements.
|Item}
% endfor %
If, within a component partial, you require rendering another component partial, you must concatenate the variable __SELF__ using the name of the partial:
Unique Identifier
If the same component is used twice in the same place, the ID property may refer to every instance.
rendering partials of code
It is possible to programmatically render partial component parts within the PHP code using renderingPartial. This will check the component for the partially named component-partial.htm and return the result as a string—another parameter to pass views variables. The exact path resolution algorithm is applied when rendering the component’s partiality in PHP in the same way as with Twig. Use # to indicate parts within the component.
$content = $this->renderPartial(‘@component-partial.htm’);
$content = $this->renderPartial(‘@component-partial.htm’, [
‘name’ => ‘John Smith’
]);
To render a partial response for the AJAX handler:
functionality onGetTemplate()
{
return [‘#someDiv’ => $this->renderPartial(‘@component-partial.htm’)];
}
Another option is to override the entire page response by returning an onRun page execution. This code will give an XML response by using the Response facade.
public role onRun()
{
$content = $this->renderPartial(‘@default.htm’);
return Response::make($content)->header(‘Content-Type’, ‘text/xml’);
}
Injecting Page Assets into Components
Components can inject asset files (CSS or JavaScript files) into layouts or pages they’re connected to. Utilize the controller’s addCss or addJs methods to connect items to CMS controllers. This can be accomplished using the onRun method of the component.
public function of Run()
{
$this->addJs(‘/plugins/acme/blog/assets/javascript/blog-controls.js’);
}
If the path in the addCss or addJs method argument starts with the letter (/) or a slash (or), it will be relative to the root of the website. If the path to the asset does not start with a slash, it is a relative path to the component’s directory.
The addCss or addJs methods offer a third argument that specifies the properties of the asset you have injected in an array.
public role onRun()
{
$this->addJs(‘/plugins/acme/blog/assets/javascript/blog-controls.js’, [‘defer’ => true]);
}
Conclusion
Using models within custom components is essential to October CMS developers looking to build solid and data-driven applications. Understanding how to organize and work using your information can provide an excellent foundation for the development process, including querying databases and managing relationships between different entities. This method of organization saves time and improves custom components’ efficiency, making them more efficient and adaptable.
Integrating models in your custom October CMS development workflow can allow for better data management and effective control of complicated systems. Once you are proficient with this feature, you can unlock the possibilities of October CMS, which allows you to develop versatile and simple applications to manage. With these strategies, you can create advanced, user-friendly elements that work seamlessly with your project. This means you’ll be able to provide top-of-the-line October CMS solutions tailored to your needs and make your development process more efficient and efficient.
Looking for a Tailored October CMS Solution? Hire Our October CMS Developers
Pooja Upadhyay
Director Of People Operations & Client Relations