Zend Framework 3 problem with redis caching - php

I am having a problem getting Redis caching working in my ZF3 application.
I have been trying to piece together how to do this from various websites, including SO and am really not sure if I am going the right way about this.
What I am doing so far is this:
In my global.php config file I have added :
...
'redis_cache' => [
'adapter' => [
'name' => 'redis',
'options' => [
'server' => [
'host' => '127.0.0.1',
'port' => 6379,
]
]
],
]
...
In my controller I have
use Zend\Cache\StorageFactory;
and then inside a method I am trying to test the cache using
$redis = StorageFactory::factory ($this->config['redis_cache']);
if ($redis->hasItem ('mykey'))
{
$value = $redis->getItem('mykey');
}
echo 'value = ' . $value;
This is not getting the value. However if I do a print_r() on $redis I can see the Redis object has been created.

In case it is of help to anyone else, this is the solution I found.
Firstly, I needed to install zend-serializer, I already had zend-cache installed.
php composer require zendframework/zend-serializer
Then in /config/autoload/global.php I added
'caches' => [
'RedisCache' => [
'adapter' => [
'name' => Redis::class,
'options' => [
'server' => [
'host' => '127.0.0.1',
'port' => '6379',
],
],
],
'plugins' => [
[
'name' => 'serializer',
'options' => [
],
],
],
],
],
In /config/application.config.php I added
'service_manager' => [
'factories' => [
\Zend\Cache\Storage\Adapter\Redis::class => InvokableFactory::class
]
]
Finally, In my controller factory I set up the dependency injection like this
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$cache = $container->get('RedisCache');
return new IndexController($cache);
}
To use the caching in my controller I added the caching to my constructor
public function __construct($cache)
{
$this->cache = $cache;
}
and in a method:
$this->cache->setItem('foo', 'bar');
echo $this->cache->getItem('foo');

Related

Api/v1 does not exist in config when running php artisan serve

I would like to build an API that does a GET request to a third party API. I created a controller that houses this logic and registered this as an HTTP end point using the JsonApiRoute::server() facade. I am absolutely new to Laravel and PHP.
However when I run php artisan serve I get the error:
Server /api/v1 does not exist in config or is not a valid class.
This is my code in routes:
JsonApiRoute::server('/api/v1')
->prefix('/api/v1')
->resources(function ($server) {
$server->resource('retrieve');
});
This is the code I have in config-> json-api-default:
return [
'resolver' => \CloudCreativity\LaravelJsonApi\Resolver\ResolverFactory::class,
'namespace' => null,
'by-resource' => true,
'model-namespace' => null,
'resources' => [
'posts' => \App\Post::class,
],
'use-eloquent' => true,
'url' => [
'host' => null,
'namespace' => '/api/v1',
'name' => 'api:v1:',
],
'controllers' => [
'transactions' => true,
'connection' => null,
],
'jobs' => [
'resource' => 'queue-jobs',
'model' => \CloudCreativity\LaravelJsonApi\Queue\ClientJob::class,
],
'encoding' => [
'application/vnd.api+json',
],
'decoding' => [
'application/vnd.api+json',
],
'providers' => [],
];
and in my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class retrieve extends Controller
{
//
public function retrieveData(Request $request){
$response = Http::withHeaders([
'api-key' => '***',
])->get('https://data.mongodb-api.com/app/data-pkrpq/endpoint/getRandom');
return response()->json(['status'=> true,'data'=> json_decode($response->body()), 'Message'=>'Successfully retrieved'], 200);
}
}

Yii2: Rest POST Request Parameters not arriving

Good morning,
I dont get any further in this Topic so i am writing a Question here.
First of all i created a DB Table with Data from the Tutorial: https://www.yiiframework.com/doc/guide/2.0/en/start-databases
Then i created a Rest Controller from that Tutorial with the Data above: https://www.yiiframework.com/doc/guide/2.0/en/rest-quick-start
The first example GET Request from the Tutorial works fine and gives me all of the data from the DB.
My Request URL: http://XX.X.X.12:XX90/country/
Now we come to my Error when trying to create a new Country in the DB via a POST Request.
When using the CURL Command from underneath the Tutorial with my Test-Data i get following error:
SQLSTATE[HY000]: General error: 1364 Field 'code' doesn't have a default value**strong text**
(
[0] => HY000
[1] => 1364
[2] => Field 'code' doesn't have a default value
)
My standard logging from rest api says that the POST Var is empty, but why?
I also tested sending POST Request via a Tool (Postman) but i get the same error.
$_GET = []
$_POST = []
$_FILES = []
$_COOKIE = []
$_SERVER = [....]
My Model:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
}
My Controller:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class CountryController extends ActiveController
{
public $modelClass = 'app\models\Country';
}
My CURL Request:
curl -i -H "Accept:application/json" -H "Content-Type:application/json" \
-XPOST "http://XX.X.X.12:XX90/countries/" \
-d '{"code": "TEST", "name": "TestCountry", "population": 01}'
My web.php Config:
<?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'name' => 'Yii2-ExtJS Rest API',
'modules' => [
'user' => [
'class' => Da\User\Module::class,
// ...other configs from here: [Configuration Options](installation/configuration-options.md), e.g.
'administrators' => ['admin'], // this is required for accessing administrative actions
// 'generatePasswords' => true,
// 'switchIdentitySessionKey' => 'myown_usuario_admin_user_key',
],
'debug' => [
'class' => 'yii\debug\Module',
'allowedIPs' => ['XX.X.X.XXX', 'XX.XXX.XXX.XXX', '127.0.0.1', '::1']
],
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'XXXXXXXXXXXXXXXX',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => \yii\symfonymailer\Mailer::class,
'viewPath' => '#app/mail',
// send all mails to a file by default.
'useFileTransport' => true,
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
// 'levels' => ['error', 'warning', 'trace', 'info'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => 'country'],
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
'allowedIPs' => ['XX.X.X.XX', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
Suggestions?
You need to declare validation rules for working with the Rest API
Thanks to #Bizley
My Country Model now:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
public function rules()
{
return [
[['code', 'name', 'population'], 'required']
];
}
}

Yii Console Script, Login to User [duplicate]

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

Yii2 - Getting unknown property: yii\console\Application::user

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

Zend Framework 2 / Doctrine authentication from 2 entities

I have 2 entities : User and Member to access different modules in my ZF2 application.
I have 2 different login forms to make the connection.
config of the Member dedicated module :
'doctrine' =>
[
'authenticationservice' =>
[
'platform' => true,
],
'authenticationstorage' =>
[
'platform' => true,
],
'authenticationadapter' =>
[
'platform' => true
],
'authentication' =>
[
'platform' =>
[
'storage' => 'Platform_Auth',
'objectManager' => EntityManager::class,
'identityClass' => Member::class,
'identityProperty' => 'login',
'credentialProperty' => 'password',
'credentialCallable' => function (Member $member, $password)
{
return ($member->getPassword() === md5($password));
}
],
]
],
And User dedicated module
'doctrine' =>
[
'authenticationservice' =>
[
'admin' => true,
],
'authenticationstorage' =>
[
'admin' => true,
],
'authenticationadapter' =>
[
'admin' => true
],
'authentication' =>
[
'admin' =>
[
'storage' => 'Admin_Auth',
'objectManager' => EntityManager::class,
'identityClass' => User::class,
'identityProperty' => 'login',
'credentialProperty' => 'password',
'credentialCallable' => function (User $user, $password)
{
return ($user->getPassword() === md5($password));
}
]
]
],
How can I use Doctrine authentication with 2 different configuration ?
Is there a way to achieve that ?
edit
I can use either one with a shared Authentication factory and extention (platform / admin) based on route ... But I don't know if it's a good idea ...
edit2
I have another error with the configured storage :
".... Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Admin_Auth in ..."
Any help would be very appreciated

Categories