How to get configuration params in Console Controller in Yii2 Framework
I try below code but its not working
Yii::$app->params['params_1']
Try This:
Code in config/params.php
<?php
return array(
'apptitle' => 'stackOverlfow',
//Define PARAMS as you need.
);
?>
You can use PARAM as below:
\Yii::$app->params['apptitle'];
Example:
echo "App title is:". \Yii::$app->params['apptitle'];
As you mentioned Basic Template Of Yii.
config/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
.
.
.
],
'params' => $params,
];
return $config;
?>
config/params.php
<?php
$params = [
'params_1' => 'YourValue'
];
return $params;
?>
SomeWhere.php
<?=Yii::$app->params['params_1'];?>
Seems that you insert your param to other conf params.php.
My helper function:
/**
* Get param value from config file.
* Получение параметра из конфигурационного файла
*
* #param string $param_name название пареметра
*
* #return string|ApicoServerErrorHttpException Значение параметра
* #throws \Exception
*/
public static function yiiparam($param_name)
{
if (isset(\Yii::$app->params[$param_name])) {
return \Yii::$app->params[$param_name];
} else {
$msg = "Can not find param in configuration file. have been search by param = " . VarDumper::export($param_name);
\Yii::error($msg, __METHOD__);
throw new ServerErrorHttpException();
}
}
Related
I would like to save the information that I am receiving in the response of a request, in this case the "access_token" field, to my mysql database, here is the code:
My controller,
here I make a post request to have the access token:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class AuthsController extends Controller
{
public function SocialAuth(Request $request)
{
$a = $request->input('auth_code');
// URL
$apiURL = 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/';
// POST Data
$postInput = [
'app_id' => '7112335319877287',
'secret' => '18f52730856f43ed821187bfa9283794ca360e',
'auth_code' => $a
];
// Headers
$headers = [
//...
];
$response = Http::withHeaders($headers)->post($apiURL, $postInput);
$statusCode = $response->getStatusCode();
$responseBody = json_decode($response->getBody(), true);
echo $statusCode; // status code
dd($responseBody); // body response
}
}
Response of my request, the value that I want to save to mysql is the access token
^ array:4 [▼
"code" => 0
"message" => "OK"
"request_id" => "202211281314430102451411010AF4AA0A"
"data" => array:3 [▼
"access_token" => "fbcaa610339b7aeb39eabf29346d06a4e7fe9"
"advertiser_ids" => array:1 [▶]
"scope" => array:18 [▶]
]
]
How can I save the access token in mysql?
create a table with the following columns, for storage:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTokenTableTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('token_table', function (Blueprint $table) {
$table->integer('id_token')->primary();
$table->string('token')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('token_table');
}
}
Use your token Model and save the data
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
// call your token Model class
use App\Models\TokenTable
class AuthsController extends Controller
{
public function SocialAuth(Request $request)
{
$a = $request->input('auth_code');
// URL
$apiURL = 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/';
// POST Data
$postInput = [
'app_id' => '7112335319877287',
'secret' => '18f52730856f43ed821187bfa9283794ca360e',
'auth_code' => $a
];
// Headers
$headers = [
//...
];
$response = Http::withHeaders($headers)->post($apiURL, $postInput);
$statusCode = $response->getStatusCode();
$responseBody = json_decode($response->getBody(), true);
echo $statusCode; // status code
//check if status code is 200
if($statusCode == 200){
TokenTable::create([
'token' => $responseBody['data']->access_token
]);
echo 'ok';
}
}
}
or this
if($statusCode == 200){
TokenTable::create([
'token' => $responseBody['data']['access_token']
]);
echo 'ok';
}
This code <?php echo Url::to(['/tasks/', 'view' => $task->id]);?> transforms into the url web/tasks?view=1 what code and where will transform output variants into the web/tasks/view/1?
Config File:
'urlManager' => [
# code...
'rules' => [
'tasks/view/<id:\d+>' => 'tasks/view',
],
Controller-Action
public function actionView($id) {
// $_GET or \Yii::$app->getRequest()->GET('id')
$id = ... int id
# code..
}
View File:
<?php echo Url::to(['/tasks/view', 'id' => $task->id]);?>
I'm trying to upload multiple images when I create a Post, but only one Image is stored in database, in server all images are saved but in my table only first image is saved but not all so I created function for upload
// Function to upload images
public function CreateGallery($model_Post, $model_Gallery)
{
$model_Post->Post_id = md5(microtime());
$model_Post->User_id = Yii::$app->user->id;
$GLRID = md5(uniqid());
// file
$GFolder = 'upload/images/'. $model_Post->Post_id .'/' ;
mkdir ($GFolder, 0777, true);
if ( $model_Post->save() ){
$model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');
$ly_GalName = uniqid();
foreach ($model_Gallery->GalleryFile as $GalleryImage) {
++$ly_GalName;
$model_Gallery->Gallery_id = ++$GLRID;
$model_Gallery->User_id = $model_Post->User_id;
$model_Gallery->Post_id = $model_Post->Post_id;
$GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);
$model_Gallery->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
}
$model_Gallery->save(false);
}
}
and inside my controller I add the function I created
public function actionCreate()
{
$model_Post = new Post();
$model_Gallery = new Gallery;
$actions_UploadImages = new ActionsUploadImages();
if ($model->load(Yii::$app->request->post()) ) {
$actions_UploadImages->CreateGallery($model_Post, $model_Gallery)
return $this->redirect(['view', 'id' => $model_Post->Post_id]);
} else {
return $this->render('create', [
'model_Post' => $model_Post,
'model_Gallery' => $model_Gallery,
]);
}
}
and my views/create my code is
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model_Post, 'Post_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model_Gallery, 'GalleryFile[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<?= $form->field($model_Post, 'Post_text')->textarea(['rows' => 2]) ?>
<?= $form->field($model_Post, 'Permission_id')->dropdownList($model_Permission->PermissionList()) ?>
<div class="form-group">
<?= Html::submitButton($model_Post->isNewRecord ? 'Create' : 'Update', ['class' => $model_Post->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
I tried to change gallery_id to AUTO_INCREMENT but still the same problem, I tried to remove if ( $model_Post->save() ), but I get error from database. Only like it's is now it's save all images on server but in table save only one image.
//// gallery model :
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "gallery".
*
* #property string $Gallery_id
* #property string $Gallery_image
* #property string $Post_id
* #property string $User_id
*
* #property Post $post
* #property Userlogin $user
*/
class Gallery extends \yii\db\ActiveRecord
{
public $GalleryFile;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'gallery';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['Gallery_id', 'Post_id', 'User_id'], 'required'],
[['Gallery_id'], 'string', 'max' => 200],
[['Gallery_image'], 'string', 'max' => 350],
[['Post_id', 'User_id'], 'string', 'max' => 300],
[['GalleryFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 5],
[['Post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['Post_id' => 'Post_id']],
[['User_id'], 'exist', 'skipOnError' => true, 'targetClass' => Userlogin::className(), 'targetAttribute' => ['User_id' => 'User_id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'Gallery_id' => 'Gallery ID',
'Gallery_image' => 'Gallery Image',
'Post_id' => 'Post ID',
'User_id' => 'User ID',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPost()
{
return $this->hasOne(Post::className(), ['Post_id' => 'Post_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(Userlogin::className(), ['User_id' => 'User_id']);
}
/**
* #inheritdoc
* #return \app\queries\GalleryQuery the active query used by this AR class.
*/
public static function find()
{
return new \app\queries\GalleryQuery(get_called_class());
}
}
you need write a new model en the for each , like that
Function
Create a new model object in the for each .
Set the $model_Gallery->save(false); in inside the foreach
// Function to upload images
public function CreateGallery($model_Post, $model_Gallery)
{
$model_Post->Post_id = md5(microtime());
$model_Post->User_id = Yii::$app->user->id;
$GLRID = md5(uniqid());
// file
$GFolder = 'upload/images/' . $model_Post->Post_id . '/';
mkdir($GFolder, 0777, true);
if ($model_Post->save()) {
$model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');
$ly_GalName = uniqid();
foreach ($model_Gallery->GalleryFile as $GalleryImage) {
$model_GalleryImage = new Gallery;
++$ly_GalName;
$model_GalleryImage->Gallery_id = ++$GLRID;
$model_GalleryImage->User_id = $model_Post->User_id;
$model_GalleryImage->Post_id = $model_Post->Post_id;
$GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);
$model_GalleryImage->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
$model_GalleryImage->save(false); //here , remove 'false' to work validations
}
}
}
Controller
when the action load the data ,it should not be like that ?
if ($model_Gallery->load(Yii::$app->request->post()) and $model_Post->load(Yii::$app->request->post())) {
//the rest of the code
}
Please note that we use save(false) to skip over validations inside the models as the user input data... with the user input
All you have to do is iterate $_FILES object using foreach loop and create new model every time. To validate code manage flag for that
I'm looking for a way to execute a little bit of JSON from my Symfony (2.6 btw) controller, moreover than an other action (post data into database)
In fact, there is an register page with a controller which put data into database and then, redirect user to another page. But i need that my controller execute too a little bit of JSON to use Mailchimp API.
I've found a lot of docs about how to render JSON response, but, it seems to me that it's not what i want to be.
There is my controller
public function registerAction(Request $request)
{
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
// Gestion du type d'utilisateur et ajout du role
$user_type = $form->get('user_profile')->get('type')->getData();
$new_role = $this->roles[$user_type];
$event = new FormEvent($form, $request);
$user = $event->getForm()->getData();
$user->addRole($new_role);
$user->getUserProfile()->setEmail($user->getEmail());
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
return $this->render('FOSUserBundle:Registration:register.html.twig', array(
'form' => $form->createView(),
));
}
There is my JSON request
{
"email_address": "$email",
"status": "subscribed",
"merge_fields": {
"FNAME": "$name",
"LNAME": "$lastname",
"DATE": "$date"
}
}
So, how can i do to execute this JSON with this controller ?
Thank you in advance for your help (and sorry for my excellent english)
You probably want to create the JSON from an array rather than try to pass variables. Try:
$data = [
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $name,
'LNAME' => $lastname,
'DATE' => $date,
],
];
$json = json_encode($data);
Then I'm assuming this data gets sent to MailChimp in a POST request? If so, you could use Guzzle to send the data to MailChimp:
First add the guzzle dependency in composer by running:
composer require guzzlehttp/guzzle
Then send the data:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['body' => $data]);
To send JSON instead of raw data, do the following:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['json' => $data]);
Depending on the response status, you can then handle the logic afterwards.
You can achieve this also using JsonResponse (Symfony\Component\HttpFoundation\JsonResponse)
use Symfony\Component\HttpFoundation\JsonResponse;
...
// if you know the data to send when creating the response
$data = [
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $name,
'LNAME' => $lastname,
'DATE' => $date,
]
];
$response = new JsonResponse($data);
return $response;
More details here https://symfony.com/doc/current/components/http_foundation.html
Im using Codeception in Yii2 to make acceptance tests and there's no way to access my models because namespaces are not working into these tests.
I have this in my tests/_bootstrap.php
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../console/config/main.php');
//
$application = new yii\console\Application( $config );
## Added (#vitalik_74)
Yii::setAlias('#tests', dirname(__DIR__));
This in my console/config/main
<?php
$params = array_merge(
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];
<?php
return [
'adminEmail' => 'admin#example.com',
'supportEmail' => 'support#example.com',
'user.passwordResetTokenExpire' => 3600,
];
And this is one of the wannabe-tests:
<?php namespace tests\acceptance;
use \AcceptanceTester;
use backend\models\User; ## I have tried writing it with a / at the beggining
class ListUserCest
{
public function _before(AcceptanceTester $I)
{
}
public function _after(AcceptanceTester $I)
{
}
public function init(AcceptanceTester $I)
{
$this->login($I);
if( User::find()->exists() )
$I->amGoingTo('List Users having at least one');
else
$I->amGoingTo('List Users having any');
}
...
I get this error when running the tests:
PHP Fatal error: Class 'backend\models\User' not found in /var/www/project/tests/acceptance/ListUserCest.php on line 21
Error: Class 'backend\models\User' not found
Please, help me, I have tried everything I know
EDIT
Now (after adding the line recommended by vitalik_74) I can use for example, \Yii methods into the tests but witout the web application configuration, just the console configuration.
I mean, I still can't use \backend\models\User and I can't neither access the Yii::$app->user status (to check if user is logged, for example).
The User model is just a common ActiveRecord model with his tableName, rules, attributeLabels, and some relational methods like getProfile().
It works out of the tests
<?php
namespace backend\models;
use common\helpers\MathHelper;
use backend\models\AntropometricData;
use Yii;
class User extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
...
Put the next code to tests/_bootstrap.php:
require('vendor/autoload.php');
require('vendor/yiisoft/yii2/Yii.php');
$config = require('config/web.php');
(new yii\web\Application($config));