Create Wordpress plugin in MVC(Kind of) + CRUD in simple way.
Arnanthachai chomphuchai
_it531413016@hotmail.com
First You need to know this vendor help you manage your data spread table not store in wp_posts or wp_meta.
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.
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
Filter and Manage method
"->" 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;
}
CONTINUE WRITE SOON...