使用任何PHP框架配合WordPress后端

v1.3.3 2016-10-27 02:28 UTC

README

此包允许您将WordPress用作后端(管理面板),并使用Eloquent检索其数据,适用于任何PHP项目或框架。

Travis Packagist Packagist

关注 @corcelphp 在Twitter上

Corcel是一个类集合,旨在使用更好的语法检索WordPress数据库数据。它使用了为Laravel框架开发的Eloquent ORM,但您可以在任何类型的PHP项目中使用Corcel,包括Laravel。

这样,您可以将WordPress用作后端(管理面板),以插入帖子、自定义类型等,您可以在前端使用任何您想要的,如Silex、Slim框架、Laravel、Zend,甚至纯PHP(为什么不呢?)。因此,只需使用Corcel从WordPress检索数据即可。

安装

要安装Corcel,只需运行以下命令

composer require jgrossi/corcel

用法

我使用Laravel

如果您正在使用Laravel,您不需要再次配置数据库。一切都已经由Laravel设置好了。因此,您只需更改config/database.php配置文件并设置您的连接。您可以使用一个连接或两个(一个用于您的Laravel应用程序,另一个用于Corcel)。您的文件将如下所示

<?php // File: /config/database.php

'connections' => [

    'mysql' => [ // this is your Laravel database connection
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'app',
        'username'  => 'admin'
        'password'  => 'secret',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
        'engine'    => null,
    ],

    'wordpress' => [ // this is your Corcel database connection, where WordPress tables are
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'corcel',
        'username'  => 'admin',
        'password'  => 'secret',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => 'wp_',
        'strict'    => false,
        'engine'    => null,
    ],
    
],

现在您应该创建自己的Post模型类。Laravel将模型类存储在app目录中,在App命名空间内(或您为其提供的名称)。您的Post类应扩展Corcel\Post并设置您正在使用的连接名称,在这种情况下为wordpress

<?php // File: app/Post.php

namespace App;

use Corcel\Post as Corcel;

class Post extends Corcel
{
    protected $connection = 'wordpress';
}

因此,现在您可以获取数据库数据

$posts = App\Post::all(); // using the 'wordpress' connection
$posts = Corcel\Post::all(); // using the 'default' Laravel connection

我使用另一个PHP框架

在这里,您必须配置数据库以满足Corcel的要求。首先,如果尚未加载,应包含Composer的autoload文件

require __DIR__ . '/vendor/autoload.php';

现在您必须设置WordPress数据库参数

$params = array(
    'database'  => 'database_name',
    'username'  => 'username',
    'password'  => 'pa$$word',
    'prefix'    => 'wp_' // default prefix is 'wp_', you can change to your own prefix
);
Corcel\Database::connect($params);

您可以指定所有Eloquent参数,但其中一些是默认的(但您可以覆盖它们)。

'driver'    => 'mysql',
'host'      => 'localhost',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => 'wp_', // Specify the prefix for WordPress tables, default prefix is 'wp_'

帖子

每次您看到Post::method()时,如果您正在使用自己的Post类(您在其中设置了连接名称),如App\Post,您应使用App\Post::method()而不是Post::method()。所有示例都假设您已经知道这种差异。

// All published posts
$posts = Post::published()->get();
$posts = Post::status('publish')->get();

// A specific post
$post = Post::find(31);
echo $post->post_title;

// Filter by meta/custom field
$posts = Post::published()->hasMeta('field')->get();
$posts = Post::hasMeta('acf')->get();

您也可以从帖子中检索元数据。

// Get a custom meta value (like 'link' or whatever) from a post (any type)
$post = Post::find(31);
echo $post->meta->link; // OR
echo $post->fields->link;
echo $post->link; // OR

更新帖子自定义字段

$post = Post::find(1);
$post->meta->username = 'juniorgrossi';
$post->meta->url = 'http://grossi.io';
$post->save();

插入自定义字段

$post = new Post;
$post->save();

$post->meta->username = 'juniorgrossi';
$post->meta->url = 'http://grossi.io';
$post->save();

高级自定义字段(ACF)

如果您想检索由高级自定义字段(ACF)插件创建的自定义字段,您必须安装corcel/acf插件,并像这样调用自定义字段

$post = Post::find(123);
echo $post->acf->some_radio_field;
$repeaterFields = $post->acf->my_repeater_name;

自定义帖子类型

您也可以处理自定义帖子类型。您可以使用type(string)方法或创建自己的类。

// using type() method
$videos = Post::type('video')->status('publish')->get();

// using your own class
class Video extends Corcel\Post
{
    protected $postType = 'video';
}
$videos = Video::status('publish')->get();

使用type()方法将使Corcel返回所有对象作为Corcel\Post。使用您的自定义类,您有自定义类、包括自定义方法和属性的优点,将所有对象作为Video等返回。

自定义帖子类型和元数据

// Get 3 posts with custom post type (store) and show its address
$stores = Post::type('store')->status('publish')->take(3)->get();
foreach ($stores as $store) {
    $storeAddress = $store->address; // option 1
    $storeAddress = $store->meta->address; // option 2
    $storeAddress = $store->fields->address; // option 3
}

单表继承

如果您选择为您的自定义帖子类型创建一个新类,则该类可以返回该帖子类型的所有实例。

//all objects in the $videos Collection will be instances of Post
$videos = Post::type('video')->status('publish')->get();

// register the video custom post type and its particular class
Post::registerPostType('video', '\App\Video')


//now all objects in the $videos Collection will be instances of Video
$videos = Post::type('video')->status('publish')->get();

您也可以为此内置类执行此操作,例如页面或帖子。只需将页面或帖子类与相关的帖子类型字符串相关联,然后该对象将返回默认对象。

这在您打算获取不同类型的文章集合时特别有用(例如,当获取菜单中定义的文章时)。

短代码

您可以通过在Post模型上调用addShortcode方法来添加shortcodes

// [gallery id="1"]
Post::addShortcode('gallery', function ($shortcode) {
    return $shortcode->getName() . '.' . $shortcode->getParameter('id');
});
$post = Post::find(1);
echo $post->content;

如果您正在使用Laravel,我们建议在App\Providers\AppServiceProvider中的boot方法中添加您的短代码处理器。

使用thunderer/shortcode库来解析短代码。更多信息,请点击这里

分类法

您可以得到特定文章的分类法,例如

$post = Post::find(1);
$taxonomy = $post->taxonomies()->first();
echo $taxonomy->taxonomy;

或者您可以使用其分类法来搜索文章

$post = Post::taxonomy('category', 'php')->first();

文章格式

您还可以获取文章格式,就像WordPress的get_post_format()函数一样

echo $post->getFormat(); // should return something like 'video', etc

页面

页面就像自定义文章类型。您可以使用Post::type('page')Page类。

// Find a page by slug
$page = Page::slug('about')->first(); // OR
$page = Post::type('page')->slug('about')->first();
echo $page->post_title;

分类法 & 分类法

获取一个分类法或分类法或从特定分类法中加载文章。有多种方法可以实现。

// all categories
$cat = Taxonomy::category()->slug('uncategorized')->posts()->first();
echo "<pre>"; print_r($cat->name); echo "</pre>";

// only all categories and posts connected with it
$cat = Taxonomy::where('taxonomy', 'category')->with('posts')->get();
$cat->each(function($category) {
    echo $category->name;
});

// clean and simple all posts from a category
$cat = Category::slug('uncategorized')->posts()->first();
$cat->posts->each(function($post) {
    echo $post->post_title;
});

附件和修订版

PostPage获取附件和/或修订版。

$page = Page::slug('about')->with('attachment')->first();
// get feature image from page or post
print_r($page->attachment);

$post = Post::slug('test')->with('revision')->first();
// get all revisions from a post or page
print_r($post->revision);

菜单

要按其别名获取菜单,请使用以下语法。菜单项将加载到nav_items变量中。目前支持的菜单项有:页面、文章、链接、分类、标签。

$menu = Menu::slug('primary')->first();

foreach ($menu->nav_items as $item) {
    // ....
    'post_title'    => '....', // Nav item name
    'post_name'     => '....', // Nav item slug
    'guid'          => '....', // Nav full url, influent by permalinks
    // ....
}

要处理多级菜单,遍历所有菜单项,将它们放在数组中的正确级别上。然后,您可以递归地遍历这些项。

这里只是一个基本示例

// first, set all menu items on their level
$menuArray = array();
foreach ($menu->nav_items as $item) {
    $parent_id = $item->meta->_menu_item_menu_item_parent;
    $menuArray[$parent_id][] = $item;
}

// now build the menu
foreach ($menuArray[0] as $item) {
    echo '.. menu item main ..';
    if (isset($menuArray[$item->ID])) {
        foreach($menuArray[$item->ID] as $subItem) {
            echo '.. show sub menu item ..';
        }
    }
}

用户

您可以使用与处理文章相同的方式操纵用户

// All users
$users = User::get();

// A specific user
$user = User::find(1);
echo $user->user_login;

身份验证

使用laravel

您必须在config/app.php中注册Corcel的身份验证服务提供程序。

'providers' => [
    // Other Service Providers

    Corcel\Providers\Laravel\AuthServiceProvider::class,
],

然后,在config/auth.php中定义用户提供程序。

'providers' => [
    'users' => [
        'driver' => 'corcel',
        'model'  => Corcel\User::class,
    ],
],

为了让Laravel的密码重置与Corcel一起工作,我们必须覆盖数据库中密码的存储方式。为此,您必须将Auth/PasswordController.php

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class PasswordController extends Controller
{
    use ResetsPasswords;

改为

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Corcel\Auth\ResetsPasswords as CorcelResetsPasswords;

class PasswordController extends Controller
{
    use ResetsPasswords, CorcelResetsPasswords {
        CorcelResetsPasswords::resetPassword insteadof ResetsPasswords;
    }

使用其他方法

您可以使用AuthUserProvider类来验证用户

$userProvider = new Corcel\Providers\AuthUserProvider;
$user = $userProvider->retrieveByCredentials(['username' => 'admin']);
if(!is_null($user) && $userProvider->validateCredentials($user, ['password' => 'admin'])) {
    // successfully login
}

运行测试

要运行phpunit测试,请执行以下命令

./vendor/bin/phpunit

如果您已安装全局phpunit命令,只需键入

phpunit

贡献

我们欢迎所有贡献来帮助改进Corcel。

在您提交拉取请求之前,请考虑以下准则

  • 在基于dev分支的新git分支中创建您的更改

git checkout -b my-fix-branch dev

  • 创建您的补丁/功能,包括适当的测试用例。

  • 运行单元测试,并确保所有测试通过。

  • 在GitHub上,向corcel:dev发送拉取请求。

许可

MIT License © Junior Grossi