Skip to content

Getting started

The following guide will help you install the Schema package inside your WordPress plugin and start using it. The guide assumes you have a basic understanding of PHP and WordPress plugin development and have Composer installed on your system.

This library implements an abstraction layer over the wpdb class and allows you to define database tables schema and generate the SQL code to create the tables.

TIP

The Schema package is designed to work independently from the framework. You can use this package in any WordPress plugin or project without the need to use the framework.

Installation

To install the Schema package, you need to add it as a dependency to your plugin. Open a terminal window and navigate to your plugin directory.

Run the following command to add the package:

bash
composer require sematico/baselibs-schema --prefer-dist --dev

TIP

The --dev flag is used because we assume you are scoping your plugin via PHP Scoper.

Basic usage

The package allows developers to define database table schemas using an object-oriented approach. This is primarily handled by the Schema class.

Defining a table

To define a table, you need to create a new instance of the Schema class and pass the table name to the constructor. The constructor accepts the table name as the first argument and a callback as the second argument. The callback will be called with the Schema instance as the argument.

php
use Sematico\Baselibs\Schema\Schema;

$schema = new Schema( 'my_table', function ( Schema $table ) {
	// Add columns, indexes and foreign keys here.
});

Creating a table

To create a table, you can use the create_table method from the Builder class. This method will generate the SQL code to create the table and execute it.

The method requires a Schema instance as the only argument. The table will then be created in the database via the wpdb class.

php
use Sematico\Baselibs\Schema\Builder;

$builder = new Builder();
$builder->create_table( $schema );

Dropping a table

To drop a table, you can use the drop_table method from the Builder class. This method will generate the SQL code to drop the table and execute it.

The method requires a Schema instance as the only argument. The table will then be dropped from the database via the wpdb class.

php
$builder->drop_table( $schema );

Truncating a table

To truncate a table, you can use the truncate_table method from the Builder class. The method requires a string as the only argument which is the name of the table to truncate.

php
$builder->truncate_table( 'my_table' );

Source code & changelog

The source code and changelog for the Schema package can be found on GitHub.