Itâs probably better if you look into the REST classes now provided that ease a LOT the work youâre doing, like ages. You probably have to write one or two lines of code overall:
which is fine, once youâve adjusted your controller to extend from the yii\rest\ActiveController you should have /api/users/<id> working without throwing a 404.
After that you can override the actions() method and unset the action you want to override, and then it will automatically pick the action method youâve implemented in the controller, similar to the following:
public function actions()
{
$actions = parent::actions();
unset($actions['view']);
return $actions;
}
public function actionView($id)
{
if ($id == Yii::$app->user->getId()) {
return User::findOne($id);
}
throw new HttpException(404);
}
You need to specify anyway the additional routes for the routes you want to support:
I just noticed that I said something wrong in my previous post:
to change or add new endpoints you have to configure the âextraPatternsâ variable: in the guide itâs not particularly clear and it seems like âpatternsâ lets you redefine existing routes, while it seems like it will just reset them (just a guess).
Since you canât use {id}, as itâs defined as a numeric value, you need to create a new one, {username}.
This hasnât been defined and it should end in an additional variable called âtokensâ together with the already existing definition of â{id}â.
Just a word of advice: as ID is normally used to indicate a numeric representation of a model, it might have been best to add a new token rather than change the semantic meaning of âidâ. This might be quite important if youâre generating the documentation off your code.
and in my ActiveController I added the following actions:
public function actionViewKey($key)
{
$user = \app\models\User::findOne(['key' => $key]);
if ($user) {
return $user;
}
throw new HttpException(404);
}
public function actionViewHash($hash)
{
$user = \app\models\User::findOne(['hash' => $hash]);
if ($user) {
return $user;
}
throw new HttpException(404);
}
I am also new to Yii, but not new to Web application Frameworks in general. I also had a srtuggle to set up RESTful Apiâs that had to use modules. Came accross many links including the above you have given. During Christmas holiday I was free and had some time to go through the Yii documentation for half a day, and saw the same it in the Yii documentation yiiframework.com/doc-2.0/guide-rest-quick-start.html under RESTFUL Web Services, thereafter, setup my API server!!! I guess I just needed some quiet time to read through the documentation, it would have saved me 2 weeks of struggle and googling.