【larveral】Laravel集成WordPress扩展包――Corcel

时间:2020-08-31  来源:WordPress  阅读:

Corcel是一个可以适用于Laravel框架的集成Wordpress的扩展包,使用wordpress的后台发布文章,通过它的接口可以在Laravel中方便的调取文章等,试用了一下,安装和使用也非常简单。

Corcel的Github地址:https://github.com/jgrossi/corcel

这里讲一下大概的过程,具体的安装和使用见github主页上的说明。


一、数据库迁徙

需要把Wordpress的数据库迁徙到Laravel的服务器上,也就是新建一个数据库,放wordpress的数据表。

在laravel的config/database.php配置文件的connections数组中,添加wordpress数据库的定义。

在阿里云CentOS上通过wget方式下载sql文件,并使用source导入sql文件到数据库,请见:wget和source导入sql文件

二、新建model类

要使用Corcel扩展包的功能,需要使用model类,这个类继承Corcel的类,如在Models文件夹下新建了一个Wp.php的模型:


 
namespace App\Models;
 
use Corcel\Post as Corcel;
 
class Wp extends Corcel
{
    protected $connection = "wordpress";
}

这里通过connection的属性定义了要连接的数据库,并且继承Corcel\Post类,实现Corcel提供的各种接口。

三、测试Laravel调取Wordpress文章

新建一个TestController的控制器,在控制器中写个测试方法:

PHP


//laravel查询wordpress文章
public function testWp()
{
    $post = Wp::find(9569);
    echo $post->post_title;
}
增加路由规则:

PHP

1
Route::get("/test/wp", ["uses"=>"TestController@testWp"]);
浏览器中打开,可以看到效果,读取到了wordpress数据库中的文章,并且输出文章标题。

更多用法请见Corcel扩展包Github主页。

补充:

重写getUrlAttribute方法:

为了方便获取博客文章的真实url,而不是形如http://www.111cn.net /?p=9562这样的url,真实的url是http://www.111cn.net /2016/03/laravel-wordpress-corcel/这样的,只需要在新建的Model中重写扩展包vendor/jgrossi/corcel/src/Post.php的getUrlAttribute方法即可,Like this:


 
namespace App\Models;
 
use Corcel\Post as Corcel;
 
class Wp extends Corcel
{
    protected $connection = "wordpress";
    protected $domain = "http://blog.tanteng.me/";
 
    //重写获取wordpress文章url方法
    public function getUrlAttribute()
    {
        return $this->domain.date("Y/m/",strtotime($this->post_date)).$this->slug."/";
    }
}
在控制器中打印:


//laravel查询wordpress文章
public function testWp()
{
    $post = Wp::find(9569);
    //dd($post);
    echo $post->post_title;
    echo "
";
    echo $post->url;
}

【larveral】Laravel集成WordPress扩展包――Corcel

http://m.bbyears.com/wangyezhizuo/95909.html

推荐访问:蜡染
相关阅读 猜你喜欢
本类排行 本类最新