First, create a databaseFirst, create a database named Yii2basic in MySQL and create a table named player. Second, the configuration 1.app/config/db.php
<?phpreturn [ ' class ' = ' yii\db\connection ', ' dsn ' = ' mysql:host=localhost;dbname=yii2basic ', ' username ' = ' root ', ' password ' + ', ' charset ' and ' utf8 ',];
Change the user name and password here to local counterparts.
2.app/config/web.php
' Urlmanager ' + = [ ' enableprettyurl ' = ' = True, ' enablestrictparsing ' = ' = ', ' showscriptname ' = > False, ' rules ' = [ [' class ' = ' Yii\rest\urlrule ', ' controller ' = ' Player '],],
Add the URL configuration under components.
3. Create a. htaccess
Create the . htaccessunder the Yii project, created under App/web, with the following contents:
Options +followsymlinksindexignore/rewriteengine onrewritecond%{request_filename}!-frewritecond%{REQUEST_ FILENAME}!-drewriterule. index.php
Third, create a controller
First, create a controller class app\controllers\PlayerController
as follows,
Namespace App\controllers;use yii\rest\activecontroller;class Usercontroller extends activecontroller{public $ Modelclass = ' App\models\player '; Public $serializer = ' Yii\rest\serializer '; Public Function checkAccess () { }}
The controller class extends from Yii\rest\activecontroller. By specifying Yii\rest\activecontroller::modelclass app\models\player
, the controller can know which model to use to acquire and process data.
Iv. Creating a Model classthen, create a model class
app\model\Player
as follows,
<?phpnamespace app\models;use yii\db\activerecord;use yii\web\link;use yii\web\linkable;use yii\helpers\Url; Class Player extends ActiveRecord implements linkable{public function fields () { return [ //Field name and property name are the same ' id ', //field named "Email", corresponding property named "email_address" ' username ', ' password ', ]; } Public Function Getlinks () { return [ link::rel_self] = url::to ([' User/view ', ' id ' = = $this ID], true), ];} }
according to the official documentation, the corresponding series of APIs has been generated and the format is referenced Yii2.0 RESTful Web Services (1)by command:
Curl-i-H "Accept:application/json" "Http://localhost/YourAppName/web/players"
will receive the following information:
[ { "id": 0, "username": "", "password": "", "_links": {"Self ": { "href": "// Localhost/first-yii/web/player/view?id=0 " } } }, { " id ": 1, " username ":" DFFDFDFD ", "password": "Sdsadsa", "_links": { "self": { "href": "http://localhost/first-Yii/web/player/ View?id=1<span style= "font-family: ' Helvetica Neue ', Helvetica, Arial, ' Hiragino Sans GB ', ' Hiragino Sans GB W3 ', ' Wenq Uanyi Micro Hei ', ' Microsoft Yahei UI ', ' Microsoft Yahei ', Sans-serif; White-space:pre-wrap; " > "</span>}}"
Using postman to test the functionality, the CD operation in the curd operation behaves normally, but the request for a single logged operation returns the following error:
{"Name": "Exception", "message": "Calling unknown Method:app\\models\\player::serializemodel ()", "code": 0, "type": "Yii\\base\\unknownmethodexception", "File": "/applications/xampp/xamppfiles/htdocs/first-yii/vendor/yiisoft/ yii2/base/component.php "," line ": 285," stack-trace ": [" #0/applications/xampp/xamppfiles/htdocs/first-yii/vendor/y Iisoft/yii2/rest/serializer.php (137): Yii\\base\\component->__call (' Serializemodel ', Array) "," #1/Applications /xampp/xamppfiles/htdocs/first-yii/vendor/yiisoft/yii2/rest/serializer.php (137): app\\models\\Player-> Serializemodel () "," #2/applications/xampp/xamppfiles/htdocs/first-yii/vendor/yiisoft/yii2/rest/controller.php ( ): Yii\\rest\\serializer->serialize (Object (App\\models\\player)) "," #3/applications/xampp/xamppfiles/htdocs /first-yii/vendor/yiisoft/yii2/rest/controller.php (): Yii\\rest\\controller->serializedata (Object (app\\ Models\\player)) "," #4/applications/xampp/xamppfiles/htdocs/first-yii/vendor/yiisoft/yii2/base/controller.php (156): Yii\\rest\\controller->afteraction (Object (Yii\\rest\\viewaction), Object (app \\models\\Player)) "," #5/applications/xampp/xamppfiles/htdocs/first-yii/vendor/yiisoft/yii2/base/module.php (454 ): Yii\\base\\controller->runaction (' View ', Array) ', ' #6/applications/xampp/xamppfiles/htdocs/first-yii/vendor /yiisoft/yii2/web/application.php (+): yii\\base\\module->runaction (' Player/view ', Array) "," #7/Applications/ xampp/xamppfiles/htdocs/first-yii/vendor/yiisoft/yii2/base/application.php (375): yii\\web\\Application-> HandleRequest (Object (yii\\web\\request)) "," #8/applications/xampp/xamppfiles/htdocs/first-yii/web/index.php (12) : Yii\\base\\application->run () "," #9 {main} "}
The error prompt calls the non-existent method, by Yii2.0 the first knowledge of the RESTful serializer know here is a method to serialize the model, return to the controller's declaration can be found to actually initialize the $serializer variable. Can be seen:
Public function serialize ($data) { if ($data instanceof Model && $data->serializemodel ()) { return $this->serializemodelerrors ($data); } ElseIf ($data instanceof arrayable) { return $this->serializemodel ($data); } elseif ($data instanceof Dataproviderinterface) { return $this->serializedataprovider ($data); } else { return $data; } }
The $data that should be passed here does not have a Serializemodel () method to findserializemodel () definition, found App/rest/serializer::serializemodel (); there is a definition here, The incoming data is not necessarily serializemodel, unless the incoming data is already a app/rest/serializer example, then commented out $data->serializemodel () This condition, to test, this time there is no error, but returned an empty result set. -------------------------------------------Update----------------------------------------for the first timethis time I have a query on the records that are not in the database, and the results of this return give a great hint:
{ "name": "Not Found", "message": "Object not Found:3", "code": 0, "status": 404, "type": "Yii\\ Web\\notfoundhttpexception "}
It is true that the database does not have a primary key of 3 of this record, so in the database to replace the primary key again to test, this time with username as the primary key discovery problem still exists.
Yii2.0 Simple API to implement restful style