Create Wordpress plugin in MVC(Kind of) + CRUD in simple way.
Arnanthachai chomphuchai
[email protected]
First You need to know this vendor help you manage your data spread table not store in wp_posts or wp_meta.
- Wordpress (of course)
- phpstorm (just recommend for autocomplete and wordpress support)
- Composer
- Redbean >= 4 (included)
- Autoload PSR-0 (included)
- Jade or Pug (not important) For make fast and flexable UI
- We CREATE TABLE By class name But...
- No worry about manage table, It's automatic CREAT, ALTER table or change TYPE of columns
- Create t
It's not fully MVC, but it can make things easier, because We do same thing all the time.
I'm serious about file size, so I avoid large ORM or framework that's have a bunch of unused code.
- Create your plugin index file.
- require this vendor.
- Ok, Ready to go.
Example: /wp-content/plugins/my-plugin/src/MyProject/Model/Book.php
<?php
namespace MyProject\Model;
use vendor\wp_infinite\Controller\ModelController;
class Book extends ModelController
{
protected $name;
protected $price = 0;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getPrice()
{
return $this->price;
}
public function setPrice($price)
{
$this->price = $price;
}
}
What if you want to custom table name? Just add property...
protected $table = 'book';
Alright! You have to see these methods first.
CRUD method
- ->insertAction();
- ->updateAction();
- ->deleteAction();
- ->readAction();
- ->readByAction();
Filter and Manage method
- ::find();
- ::findBy();
- ::findOneBy();
- ::findAll();
- ::findLike();
- ::count()();
- ::countBy();
- ::purge();
"->" Need to declare instance first. (new Book())
"::" Work both declare or not declare instance. (Book::find(), $book::find())
Note:
CRUD methods return bool;
Filter methods return array;
$book = new \MyProject\Model\Book();
$book->setName('Harry Potter');
$book->setPrice(1200);
$book->insertAction();
You may notics 'insertAction();' and it's going to do couple thing Yes, It will automatic create table, take care column type and insert record for you. thanks for readbean.
$book = new \MyProject\Model\Book();
$book->readAction(5); //read id 5
echo $book->getName();
echo $book->getPrice();
CRUD Action also return bool or id of row, So you can make condition too
$idToRead = 2;
$book = new \MyProject\Model\Book();
if ($book->readAction($idToRead)) {
//Do stuff
} else {
echo 'Can\'t read ID: '.$idToRead;
}
$book = new \MyProject\Model\Book();
if ($book->deleteAction(3))
echo "Deleted!";
else
echo "Can't Delete";
Filter return object or array of data
$books = \MyProject\Model\Book::findAll();
foreach ($books as $book) {
echo $book->name;
}
- Paginate (php / jQuery with ajax)
- Ajax Provider: Jquery and AngularJS
- Some Wordpress model (Page, Post, Route)
CONTINUE WRITE SOON...