Twig loader in constructor - constructor

I try to make my own Response class using twig
<?php
namespace app\library;
class Response
{
public function __construct($temp, $data)
{
$loader = new Twig_Loader_Filesystem('app/views');
$twig = new Twig_Environment($loader);
print $twig->render($temp, $data);
}
}
But when I try to use it
use app\library\Response;
error_reporting(E_ALL);
require_once "vendor/autoload.php";
$arr = array('name'=>'Bob', 'surname'=>'Dow', 'gender'=>'male','age'=>'25');
new Response('temp.php', $arr);
It gives me
Fatal error: Class 'app\library\Twig_Loader_Filesystem' not found in /var/www/PHP/app/library/Response.php on line 12
Where the mistake?

Please check carefully the error. It says that class 'app\library\Twig_Loader_Filesystem' doesn't exists. Your Response class is under app\library namespace so every class which you try to instantiate there will be looked inside this namespace as well. Basically it's the same as write
$loader = new app\library\Twig_Loader_Filesystem('app/views');
$twig = new app\library\Twig_Environment($loader);
Generally in this case you have to either type the full name of a class including its namespace or make the shorthand with the help of use statement like you did for instantiating Response class.
In your particular case classes Twig_Loader_Filesystem and Twig_Environment exist in a global namespace so you could either add \ in front of classes to state that these classes are located in a global namespace:
$loader = \Twig_Loader_Filesystem('app/views');
$twig = \Twig_Environment($loader);
or create a shorthand like this:
use Twig_Loader_Filesystem;
use Twig_Environment;

Related

Why ths php dynamic object class creation is not working?

I am trying to create a class (working as factory class) in my Zend Expressive APP as follows:
declare(strict_types=1);
namespace App\Install\Factory;
use App\Install\Model as Models;
use App\Install\Abstracts\AttributeInterface;
class AttributeEntityFactory{
public static function create($type1 ='Attribute') : AttributeInterface
{
$resolvedClass = "Models\\$type1";
$resolvedClass1 = 'Models\\'.$type1;
//return new $resolvedClass();
//return new $resolvedClass1();
return new Models\Attribute();
}
}
The above code works perfectly for me. However, if try to use any of the other two return statements it shows
Class 'Models\Attribute' not found
How can I achieve dynamic instantiation?
The attribute class code is as follows:
namespace App\Install\Model;
use App\Install\Abstracts\AttributeInterface;
class Attribute implements AttributeInterface
{
protected $attribute;
public function setAttribute($attribute)
{
$this->attribute = $attribute;
}
public function getAttribute()
{
return $this->attribute;
}
}
My PHP version is:
PHP 7.2.13 (cli) (built: Dec 14 2018 04:20:16) ( NTS )
you may need to pass in the full namespace?
"App\Install\Model\" . $type1;
and more...
the model Attribute you have is in the namespace App\Install\Model, and the object you are trying to create is from Models\\ . $type1
maybe you need to change Models to Model
Personally, I would avoid such factory implementation because of several reasons:
It involves magic.
Less predictable code.
Harder to read for both humans and IDE's (E.g: PHPStorm would not find the usages of Attribute class in such code when you need to find it)
Harder to analyze using static analyzers
Instead, I would rewrite this to a more explicit factory, even if I had dozens of different classes in App\Install\Model namespace:
<?php declare(strict_types=1);
namespace App\Install\Factory;
use App\Install\Model as Models;
class AttributeEntityFactory
{
public static function create($type = 'Attribute') : AttributeInterface
{
switch ($type) {
case 'Attribute':
return new Models\Attribute();
case 'SomethingElse':
return new Models\SomethingElse();
default:
throw new \InvalidArgumentException(
sprintf('An unknown type %s requested from %s', $type, __METHOD__)
);
}
}
}
As a rule of thumb:
Never compose classnames / namespaces using strings concatenated with variables / parameters / constants whatever.
Never call methods in such way, too.
You'll thank me when your application/business/codebase grows enough.

how to use dynemodb with lumen or laravel

I want to use dynemodb and mysql both with lumen.
I have follow below steps,
https://github.com/aws/aws-sdk-php-laravel
from above url I have add package for aws sdk for lumen
and add my accesskey and secret key in .env file
in bootstrap/app.php
I have add $app->register(Aws\Laravel\AwsServiceProvider::class);
Now I want to use dynemodb with lumen to execute query
for execute dynemodb query same as eloquent I have used below package.
https://github.com/baopham/laravel-dynamodb
now I have write my code in model as below,
<?php
namespace App\Models;
use BaoPham\DynamoDb\Facades\DynamoDb;
use BaoPham\DynamoDb\DynamoDbModel;
class CategoryMaster extends BaoPham\DynamoDb\DynamoDbModel
{
protected $table = 'category_master';
protected $fillable = ['id', 'category_name'];
public static function listname()
{
$model = DynamoDbModel::where(['category_name' => 'blue']);
$query = $model->get();
echo"<pre>";print_r($query);die;
}
}
it gives me arror like below,
FatalErrorException in CategoryMaster.php line 8:
Class 'App\Models\BaoPham\DynamoDb\DynamoDbModel' not found
can you help me to resolve thais issue to use dynemodb
I implemented dynamodb in laravel project using baopham package.
In .env file define dynamodb credentials
DYNAMODB_CONNECTION=aws
DYNAMODB_KEY=***
DYNAMODB_SECRET=****
DYNAMODB_REGION=us-east-1
In Model file
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends \BaoPham\DynamoDb\DynamoDbModel
{
protected $table = 'Users'; //table name
protected $guarded = [];
}
In controller file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User; //include your model file
class UserController extends Controller
{
public function index()
{
$user = User::all(); // to get all data from user table
return view('products.index')->with('user', $user);
}
}
for more referance refer https://github.com/baopham/laravel-dynamodb query section.
I found my solution,
I have followed below site step by step and I am able to connect to dynemo db with lumen and able to fire eloquent queries
https://github.com/aws/aws-sdk-php-laravel
https://github.com/baopham/laravel-dynamodb
https://github.com/laravelista/lumen-vendor-publish

The _redirect() function in zend framework

I made a file in library/My/Utils/Utils.php. The content of the file is :
class My_Utils_Utils{
public function test(){
$this->_redirect('login');
}
}
This class is called from a layout; the problem is with the _redirect(); I get this error : The page isn't redirecting properly. My question is how call the _redirect() function from a class made by you in ZEND framework 1 .
Thanks in advance.
Use redirect() instead of _redirect(). Usage is:
$this->redirect(<action>, <controller>, <module>, <param>);
In your case $this->redirect('login'); should do the trick.
You can use the redirector action-helper, which you can get statically from the HelperBroker using:
// get the helper
$redirectHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
// call methods on the helper
$redirect->gotoUrl('/some/url');
It should be noted, however, that the layout is considered part of the view layer. Typically, any checks that result in a redirect should probably take place earlier in the request dispatch-cycle, typically in a controller or in a front-controller plugin.
The _redirect function is provided by the class Zend_Controller_Action. You can fix this in two ways :
Extend Zend_Controller_Action and use _redirect
class My_Utils_Utils extends Zend_Controller_Action {
public function test(){
$this->_redirect('login');
}
}
in layout:
$request = Zend_Controller_Front::getInstance()->getRequest();
$response = Zend_Controller_Front::getInstance()->getResponse()
$util = new My_Utils_Utils($request, $response); // The constructor for Zend_Controller_Action required request and response params.
$util->test();
Use gotoUrl() function Zend_Controller_Action_Helper_Redirector::gotoUrl()
$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl('login');
//in layout :
$util = new My_Utils_Utils();
$util->test();

Doctrine 2 namespace issue

I'm using Zend Framework 1 with the Bisna library to integrate Doctrine 2. I generated my Entities from my database model with the Doctrine 2 CLI. This is all working fine, except for the setter methods for associated records. The argument they accept must be of a specific namespace (\Category here).
class Article
{
public function setCategory(\Category $category = null) {
$this->category = $category;
return $this;
}
}
However, when I do this:
$article = $this->em->getRepository('\Application\Entity\Article')->find(1);
$category = new \Application\Entity\Category();
$category->SetName('New Category');
$article->setCategory($category);
I get the following fatal error: Argument 1 passed to Application\Entity\CategoryField::setCategory() must be an instance of Category, instance of Application\Entity\Category given.
When I change the setter method to accept \Application\Entity\Category objects, it's working of course. Should I do this for every generated method, or are there other options? This is the first time I'm using namespaces, so it might be something simple.
You can always add this to the top of your class file: use \Application\Entity\Category; and then simply reference it later like so: public function setCategory(Category $category = null)
Check out: http://php.net/manual/en/language.namespaces.importing.php for more info about use
Otherwise you would have to reference the full namespace otherwise your application does not know that \Category is a reference to \Application\Entity\Category

creating functions in CodeIgniter controllers

I have a CodeIgniter application, but one of my controllers must call a data processing function that I have also written myself. The only problem is I can't seem to figure out how to do this. Looking through the user guide it seems that I should put my function inside the class declaration, and prefix it with an underscore (_) so that it cannot be called via the url. However, this is not working. Here's an example of what I mean:
<?php
class Listing extends Controller
{
function index()
{
$data = "hello";
$outputdata['string'] = _dprocess($data);
$this->load->view('view',$outputdata);
}
function _dprocess($d)
{
$output = "prefix - ".$d." - suffix";
return $output
}
}
?>
The page keeps telling me I have a call to an undefined function _dprocess()
How do I call my own functions?
Thanks!
Mala
Edit:
I've gotten it to work by placing the function outside of the class declaration. Is this the correct way of doing it?
This line is creating problem for you:
$outputdata['string'] = _dprocess($data);
Replace with:
$outputdata['string'] = $this->_dprocess($data);