環境配置:
開啟伺服器偽靜態
本處以apache為例,查看apache的conf目錄下httpd.conf,找到下面的程式碼
LoadModule rewrite_module modules/mod_rewrite.so
將其前面的#去掉,如果沒有找到。
找到程式碼
<Directory "C:/phpStudy/Apache/cgi-bin"><span> AllowOverride All Options None </span><span>Require</span><span> all granted </span></Directory>
將原本的AllowOverride None改為AllowOverride All。
然後在站點根目錄下建立一個.htaccess文件,內容如下:
<IfModule mod_rewrite.c><span> Options </span>+<span>FollowSymlinks RewriteEngine On RewriteCond </span>%{REQUEST_FILENAME} !-<span>d RewriteCond </span>%{REQUEST_FILENAME} !-<span>f RewriteRule </span>. index.<span>php </span></IfModule>.htaccess
。 YII2實際操作:1、設定URL規則及modules
(1)新建modules資料夾,實行api介面版本控制。例如V1版本、V2版本…在v1資料夾下新建controllers資料夾(控制器)、models資料夾(模型)、Module.php設定檔。
Module.php檔案如下:
<span> 1</span> <?<span>php </span><span> 2</span><span>namespace api\modules\v1; </span><span> 3</span><span> 4</span><span>class</span> Module <span>extends</span><span> \yii\base\Module </span><span> 5</span><span>{ </span><span> 6</span><span> 7</span><span>public</span><span>$controllerNamespace</span> = 'api\modules\v1\controllers'<span>; </span><span> 8</span><span> 9</span><span>public</span><span>function</span><span> init() </span><span>10</span><span> { </span><span>11</span> parent::<span>init(); </span><span>12</span><span> } </span><span>13</span> }
第2行和第7行隨版本擴充而變化(v1->v2...)。
(2)設定config資料夾下的main.php檔案
<span> 1</span> <?<span>php </span><span> 2</span><span>$params</span> = <span>array_merge</span>(<span>require</span> (__DIR__ . '/../../common/config/params.php'), <span>require</span> (__DIR__ . '/../../common/config/params-local.php'), <span>require</span> (__DIR__ . '/params.php'), <span>require</span> (__DIR__ . '/params-local.php'<span>)); </span><span> 3</span><span> 4</span><span>return</span><span> [ </span><span> 5</span> 'id' => 'app-api', <span> 6</span> 'basePath' => <span>dirname</span>(__DIR__), <span> 7</span> 'bootstrap' =><span> [ </span><span> 8</span> 'log' <span> 9</span> ], <span>10</span> 'modules' =><span> [ </span><span>11</span> 'v1' =><span> [ </span><span>12</span> 'class' => 'api\modules\v1\Module' <span>13</span> ], <span>14</span> 'v2' =><span> [ </span><span>15</span> 'class' => 'api\modules\v2\Module' <span>16</span><span> ] </span><span>17</span> ], <span>18</span> 'controllerNamespace' => 'api\controllers', <span>19</span> 'components' =><span> [ </span><span>20</span> 'user' =><span> [ </span><span>21</span> 'identityClass' => 'common\models\User', <span>22</span> 'enableAutoLogin' => <span>false</span>, <span>23</span> 'enableSession' => <span>false</span>, <span>24</span> 'loginUrl' => <span>null</span><span>25</span> ], <span>26</span> 'urlManager' =><span> [ </span><span>27</span> 'enablePrettyUrl' => <span>true</span>, <span>//</span><span> 启用美化URL</span><span>28</span> 'enableStrictParsing' => <span>true</span>, <span>//</span><span> 是否执行严格的url解析</span><span>29</span> 'showScriptName' => <span>false</span>, <span>//</span><span> 在URL路径中是否显示脚本入口文件</span><span>30</span> 'rules' =><span> [ </span><span>31</span><span> [ </span><span>32</span> 'class' => 'yii\rest\UrlRule', <span>33</span> 'controller' =><span> [ </span><span>34</span> 'v1/site' <span>35</span><span> ] </span><span>36</span> ], <span>37</span><span> [ </span><span>38</span> 'class' => 'yii\rest\UrlRule', <span>39</span> 'controller' =><span> [ </span><span>40</span> 'v2/site' <span>41</span><span> ] </span><span>42</span><span> ] </span><span>43</span><span> ] </span><span>44</span> ], <span>45</span> 'log' =><span> [ </span><span>46</span> 'traceLevel' => YII_DEBUG ? 3 : 0, <span>47</span> 'targets' =><span> [ </span><span>48</span><span> [ </span><span>49</span> 'class' => 'yii\log\FileTarget', <span>50</span> 'levels' =><span> [ </span><span>51</span> 'error', <span>52</span> 'warning' <span>53</span><span> ] </span><span>54</span><span> ] </span><span>55</span><span> ] </span><span>56</span> ], <span>57</span> 'errorHandler' =><span> [ </span><span>58</span> 'errorAction' => 'site/error' <span>59</span><span> ] </span><span>60</span> ], <span>61</span> 'params' => <span>$params</span><span>62</span> ];
2、建立一個模型
資料庫準備一個名為mxq_guide的資料表
<span>CREATE TABLE `mxq_guide` ( `id` int(</span>11) NOT <span>NULL</span> AUTO_INCREMENT,<span> `imgurl` varchar(</span>255) <span>DEFAULT</span><span>NULL </span>COMMENT '图片路径'<span>,</span><span><br> `status` int(</span><span>11) </span><span>DEFAULT</span><span>NULL</span><span> COMMENT '1启用 0禁用',<br></span><span> `flag` int(</span><span>11) </span><span>DEFAULT</span><span>NULL</span><span> COMMENT '1安卓 2苹果',</span><span><br> PRIMARY </span><span>KEY</span><span> (`id`) <br> ) ENGINE</span><span>=MyISAM AUTO_INCREMENT=24 </span><span>DEFAULT</span><span> CHARSET=utf8 COMMENT='APP导航图';</span>
建立後請注意及時往資料庫中新增幾條資料資訊。
透過鷹架gii來創建guide.php模型(使用方法請看
yii2權威指南
)。產生後的檔案注意改寫,修改為以下形式以滿足RESTful的需求。之後從models資料夾中轉移到v1/models資料夾中,並注意命名空間的修改。
<span> 1</span> <?<span>php </span><span> 2</span><span>namespace api\modules\v1\models; </span><span> 3</span><span> 4</span><span>use</span><span> Yii; </span><span> 5</span><span>use</span><span> yii\db\ActiveRecord; </span><span> 6</span><span>use</span><span> yii\web\IdentityInterface; </span><span> 7</span><span> 8</span><span>/*</span><span>* </span><span> 9</span><span> * This is the model class for table "{{%guide}}". </span><span>10</span><span> * </span><span>11</span><span> * @property integer $id </span><span>12</span><span> * @property string $imgurl </span><span>13</span><span> * @property integer $status </span><span>14</span><span> * @property integer $flag </span><span>15</span><span>*/</span><span>16</span><span>class</span> Guide <span>extends</span> ActiveRecord <span>implements</span><span> IdentityInterface </span><span>17</span><span>{ </span><span>18</span><span>19</span><span>public</span><span>static</span><span>function</span> findIdentityByAccessToken(<span>$token</span>, <span>$type</span> = <span>null</span><span>) </span><span>20</span><span> { </span><span>21</span><span>return</span><span>static</span>::<span>findOne([ </span><span>22</span> 'access_token' => <span>$token</span><span>23</span><span> ]); </span><span>24</span><span> } </span><span>25</span><span>26</span><span>public</span><span>function</span><span> getId() </span><span>27</span><span> { </span><span>28</span><span>return</span><span>$this</span>-><span>id; </span><span>29</span><span> } </span><span>30</span><span>31</span><span>public</span><span>function</span><span> getAuthKey() </span><span>32</span><span> { </span><span>33</span><span>return</span><span>$this</span>-><span>authKey; </span><span>34</span><span> } </span><span>35</span><span>36</span><span>public</span><span>function</span> validateAuthKey(<span>$authKey</span><span>) </span><span>37</span><span> { </span><span>38</span><span>return</span><span>$this</span>->authKey === <span>$authKey</span><span>; </span><span>39</span><span> } </span><span>40</span><span>41</span><span>public</span><span>static</span><span>function</span> findIdentity(<span>$id</span><span>) </span><span>42</span><span> { </span><span>43</span><span>return</span><span>static</span>::findOne(<span>$id</span><span>); </span><span>44</span><span> } </span><span>45</span><span>46</span><span>public</span><span>static</span><span>function</span><span> tableName() </span><span>47</span><span> { </span><span>48</span><span>return</span> '{{%guide}}'<span>; </span><span>49</span><span> } </span><span>50</span><span>51</span><span>public</span><span>function</span><span> rules() </span><span>52</span><span> { </span><span>53</span><span>return</span><span> [ </span><span>54</span><span> [ </span><span>55</span><span> [ </span><span>56</span> 'imgurl', <span>57</span> 'status', <span>58</span> 'flag' <span>59</span> ], <span>60</span> 'required' <span>61</span> ], <span>62</span><span> [ </span><span>63</span><span> [ </span><span>64</span> 'status', <span>65</span> 'flag' <span>66</span> ], <span>67</span> 'integer' <span>68</span> ], <span>69</span><span> [ </span><span>70</span><span> [ </span><span>71</span> 'imgurl' <span>72</span> ], <span>73</span> 'string', <span>74</span> 'max' => 255 <span>75</span><span> ] </span><span>76</span><span> ]; </span><span>77</span><span> } </span><span>78</span><span>79</span><span>public</span><span>function</span><span> attributeLabels() </span><span>80</span><span> { </span><span>81</span><span>return</span><span> [ </span><span>82</span> 'id' => Yii::t('app', 'ID'), <span>83</span> 'imgurl' => Yii::t('app', 'imgurl'), <span>84</span> 'status' => Yii::t('app', 'status'), <span>85</span> 'flag' => Yii::t('app', 'flag'<span>) </span><span>86</span><span> ]; </span><span>87</span><span> } </span><span>88</span> }
<span> 1</span> <?<span>php </span><span> 2</span><span>namespace api\modules\v1\controllers; </span><span> 3</span><span> 4</span><span>use</span><span> Yii; </span><span> 5</span><span>use</span><span> yii\rest\ActiveController; </span><span> 6</span><span>use</span><span> yii\filters\auth\CompositeAuth; </span><span> 7</span><span>use</span><span> yii\filters\auth\QueryParamAuth; </span><span> 8</span><span>use</span><span> yii\data\ActiveDataProvider; </span><span> 9</span><span>10</span><span>class</span> SiteController <span>extends</span><span> ActiveController </span><span>11</span><span>{ </span><span>12</span><span>13</span><span>public</span><span>$modelClass</span> = 'api\modules\v1\models\guide'<span>; </span><span>14</span><span>15</span><span>public</span><span>$serializer</span> =<span> [ </span><span>16</span> 'class' => 'yii\rest\Serializer', <span>17</span> 'collectionEnvelope' => 'items' <span>18</span><span> ]; </span><span>19</span><span>20</span><span>//</span><span> public function behaviors() </span><span>21</span><span> // { </span><span>22</span><span> // $behaviors = parent::behaviors(); </span><span>23</span><span> // $behaviors['authenticator'] = [ </span><span>24</span><span> // 'class' => CompositeAuth::className(), </span><span>25</span><span> // 'authMethods' => [ </span><span>26</span><span> // QueryParamAuth::className() </span><span>27</span><span> // ] </span><span>28</span><span> // ]; </span><span>29</span><span> // return $behaviors; </span><span>30</span><span> // }</span><span>31</span><span>public</span><span>function</span><span> actions() </span><span>32</span><span> { </span><span>33</span><span>$actions</span> = parent::<span>actions(); </span><span>34</span><span>//</span><span> 注销系统自带的实现方法</span><span>35</span><span>unset</span>(<span>$actions</span>['index'], <span>$actions</span>['update'], <span>$actions</span>['create'], <span>$actions</span>['delete'], <span>$actions</span>['view'<span>]); </span><span>36</span><span>return</span><span>$actions</span><span>; </span><span>37</span><span> } </span><span>38</span><span>39</span><span>public</span><span>function</span><span> actionIndex() </span><span>40</span><span> { </span><span>41</span><span>$modelClass</span> = <span>$this</span>-><span>modelClass; </span><span>42</span><span>$query</span> = <span>$modelClass</span>::<span>find(); </span><span>43</span><span>return</span><span>new</span><span> ActiveDataProvider([ </span><span>44</span> 'query' => <span>$query</span><span>45</span><span> ]); </span><span>46</span><span> } </span><span>47</span><span>48</span><span>public</span><span>function</span><span> actionCreate() </span><span>49</span><span> { </span><span>50</span><span>$model</span> = <span>new</span><span>$this</span>-><span>modelClass(); </span><span>51</span><span>//</span><span> $model->load(Yii::$app->getRequest() </span><span>52</span><span> // ->getBodyParams(), '');</span><span>53</span><span>$model</span>->attributes = Yii::<span>$app</span>->request-><span>post(); </span><span>54</span><span>if</span> (! <span>$model</span>-><span>save()) { </span><span>55</span><span>return</span><span>array_values</span>(<span>$model</span>->getFirstErrors())[0<span>]; </span><span>56</span><span> } </span><span>57</span><span>return</span><span>$model</span><span>; </span><span>58</span><span> } </span><span>59</span><span>60</span><span>public</span><span>function</span> actionUpdate(<span>$id</span><span>) </span><span>61</span><span> { </span><span>62</span><span>$model</span> = <span>$this</span>->findModel(<span>$id</span><span>); </span><span>63</span><span>$model</span>->attributes = Yii::<span>$app</span>->request-><span>post(); </span><span>64</span><span>if</span> (! <span>$model</span>-><span>save()) { </span><span>65</span><span>return</span><span>array_values</span>(<span>$model</span>->getFirstErrors())[0<span>]; </span><span>66</span><span> } </span><span>67</span><span>return</span><span>$model</span><span>; </span><span>68</span><span> } </span><span>69</span><span>70</span><span>public</span><span>function</span> actionDelete(<span>$id</span><span>) </span><span>71</span><span> { </span><span>72</span><span>return</span><span>$this</span>->findModel(<span>$id</span>)-><span>delete(); </span><span>73</span><span> } </span><span>74</span><span>75</span><span>public</span><span>function</span> actionView(<span>$id</span><span>) </span><span>76</span><span> { </span><span>77</span><span>return</span><span>$this</span>->findModel(<span>$id</span><span>); </span><span>78</span><span> } </span><span>79</span><span>80</span><span>protected</span><span>function</span> findModel(<span>$id</span><span>) </span><span>81</span><span> { </span><span>82</span><span>$modelClass</span> = <span>$this</span>-><span>modelClass; </span><span>83</span><span>if</span> ((<span>$model</span> = <span>$modelClass</span>::findOne(<span>$id</span>)) !== <span>null</span><span>) { </span><span>84</span><span>return</span><span>$model</span><span>; </span><span>85</span> } <span>else</span><span> { </span><span>86</span><span>throw</span><span>new</span> NotFoundHttpException('The requested page does not exist.'<span>); </span><span>87</span><span> } </span><span>88</span><span> } </span><span>89</span><span>90</span><span>public</span><span>function</span> checkAccess(<span>$action</span>, <span>$model</span> = <span>null</span>, <span>$params</span> =<span> []) </span><span>91</span><span> { </span><span>92</span><span>//</span><span> 检查用户能否访问 $action 和 $model </span><span>93</span><span> // 访问被拒绝应抛出ForbiddenHttpException </span><span>94</span><span> // var_dump($params);exit;</span><span>95</span><span> } </span><span>96</span> }
20~30行註解的程式碼是基於RESTful架構的access_token認證,目前還未測試通過,後續補充。
至此,基於YII2的所有配置已基本完成,接下來介紹api介面測試工具及方法。RESTful的測試工具PostMAN:
首先介紹postman這款插件,是基於Google瀏覽器的一款模擬請求的實用插件。具體使用,在下面測試過程中涉及截圖,介紹不足之處請見諒,自己也是第一次使用。
推薦使用上面的APP版本,便於後續封裝自己寫好的api接口,下面的是網頁版本。YII2支援的RESTful有四種請求方式:GET檢視訊息,POST建立訊息,PUT更新訊息,DELETE刪除訊息。
下面開始示範四種請求資料的方式。 (只是截圖示範效果,具體使用還需要大家自己去摸索。)
此處示範的是GET方法請求資料庫的資料。對應的是modules/controllers/SiteController/actionIndex方法。請大家注意最上面方框內的URL位址,rest預設將控制器進行複數請求http://api.mxq.com/v1/sites,這裡就是rest的預設規則。
打*星號位置顯示的是正常的效果,如若出現錯誤,大家可以去
YII權威指南——錯誤
檢查錯誤原因。 YII2的ActiveController預設實現了資料的分頁效果。 此處示範的是POST方法新建資料庫的資料。對應的是modules/controllers/SiteController/actionCreate方法。 如果在資料庫的資料層寫好資料校驗規則,此處提交資料不符合要求的時候就會顯示對應的錯誤。這也是REST的優點之一。例如如下情況,flag我定義的是int型: 接下來示範的是PUT方法更新資料庫的資料。對應的是modules/controllers/SiteController/actionUpdate方法。 此處請大家再次注意最上面的URL:http://api.mxq.com/v1/sites/15 此處15代表的是資料庫id為15的數據,表示更新資料庫ID為15的數據資訊。請大家一定要注意。 RESTful在使用更新和刪除資料操作的時候,id不能一表單的形式提交,必須緊跟在URL之後。 接下來示範的是DELETE方法刪除資料庫的資料。對應的是modules/controllers/SiteController/actionDelete方法。 當回傳值為1的時候表示的就是刪除操作執行成功。具體原理請大家仔細觀察sitecontroller控制器內的功能。 以上就是基於yii2的RESTful的一些簡單介紹、實作方法、測試結果。有什麼不正確或遺漏的地方,歡迎大家來補充。後續也會在此基礎上進行更新。本人第一次接觸yii2框架和RESTful架構,表達如有不對之處,請大家見諒。
以上就介紹了Yii2 advanced版API介面開發 基於RESTful架構的 配置、實作、測試,包括了面向的內容,希望對PHP教學有興趣的朋友有幫助。