Doctrine 2 namespace issue - namespaces

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

Related

CakePHP static name of controller

I'm probably missing something really obvious here, but is there a function in CakePHP (I'm on 3.8) that returns the name of a controller without creating an instance of the class?
An instanced controller can call this function:
echo $this->name;
But what I'd like to be able to do, is avoid typing the controller name as a string in, say, an HTML->link(); ie a static call something like:
echo $this->Html->link(
'Dashboard',
['controller' => DashboardsController::name, 'action' => 'index']
);
The reason is that I'm refactoring a couple of controllers and am having to find and replace all of those strings by hand. I come from a .Net background and CakePHP is pretty new to me, so if there's a better (more cakeish) way to carry out the refactoring than the question I'm asking, then I'd be really glad to hear it.
Nothing in the documents is leaping out at me, but I've a feeling there should be a simple answer.
The namespace of a class can be retrieved using ::class property. Checkout the following example:
DashboardsController::class // Cake/Controllers/DashboardController
The name without the namespace can be retrieved with ReflectionClass:
$function = new \ReflectionClass(DashboardsController::class);
var_dump($function->inNamespace());
var_dump($function->getShortName());
Shortname can be used to get the class without namespace:
namespace App;
class Test {
public static function name(){
$function = new \ReflectionClass(self::class);
return $function->getShortName();
}
}
var_dump(Test::name());
Checkout the docs: https://www.php.net/manual/en/language.oop5.constants.php#example-186
Reflection: https://www.php.net/manual/en/reflectionclass.getname.php

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 create a model object in yii2 by string name?

I need to create a model by string name that it is a variable.
function($modelName){
$modelName= "backend\\models\\".$modelName;
$modelClass = Yii::createObject([
'class' => $modelName,
]);
$model = $modelClass::find();
}
when I pass Book(it is extracted form DB) as modelName to function, it throws an error: Class backend\models\Book does not exist.
but when I write $modelName= "backend\\models\\Book"; it works fine.
I know it is because of run time and compile time. but I don't know how to solve it. because $modelName is Characterized at run time.
You are accessing to a static method using an object. You should access to the static method just using the class name eg:
$modelName = 'backend\models\\' . $modelName;
$model = $modelName::find();
And remember that $modelName::find() don't return a model but just the query object for a model. To obtain a model you should use eg: $modelName::find()->where(['id'=>$your_value])->one();

Laravel - Eloquent: Polymorphic relations with namespace

My situation is: a Calendar belongs to a Customer or Salesman
Because I also have classes like Event and File, I used the namespace App\Models for all my model classes.
so I set up the polymorphic relation:
in Calender.php
public function user() {
return $this->morphTo();
}
in Customer.php and Salesman.php
public function calendars() {
return $this->morphMany('App\Models\Calendar', 'user');
}
Now when i do
$calendar= Calendar::find(1); //calendar from a salesman
$calendar->user; //error here
...
I get this error message:
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Class 'salesman' not found
I noticed that 'salesman' is low cased, maybe this is the problem?
and this is what I get from Laravels stacktrace
open: /var/www/cloudcube/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
// foreign key name by using the name of the relationship function, which
// when combined with an "_id" should conventionally match the columns.
if (is_null($foreignKey))
{
$foreignKey = snake_case($relation).'_id';
}
$instance = new $related; //HIGHLIGHTED
I had a similar error before on this line, when I was messing with the namespaces, so I guess it has something to do with that. Is there any way I can tell the morphTo() method to use the correct namespace?
Or is it something else causing this issue?
Also found this solution, but can't seem to get it working:
Polymorphic Eloquent relationships with namespaces
I found a solution that worked for me.
I always define relationships with the correct namespace, for example in Calendar:
public function events() {
return $this->hasMany('App\Models\Event');
}
My problem consisted out of 2 complications:
$calendar->user() with the morphTo(...) function was not working because my models were in a namespace, and morphTo(...) had no way of giving this namespace.
$salesman->calenders()->get() returned and empty list, although my relations in the database were there. I found out this is because of bindings with the query.
Solution for 1. : Writing a custom morphTo(...) function in Calendar to override the one of Laravel. I used the source of Laravels morphTo(...) as a base. The final statement of this function is return $this->belongsTo($class, $id);
There $class must be the namespaced class name. I used basic string operations to pull that off.
Solution for 2. : Writing a custom morphMany(...) function in Salesman and letting it return a MyMorphMany(...) similar to what Polymorphic Eloquent relationships with namespaces described.
The problem here is that $query that is passed to the MyMorphMany constructor has the wrong (namespaced) binding. It will look for where user_type = "App\\Models\\Salesman".
To fix this I used a custom getResults() function in MyMorphMany which overrides the default Laravels implementation, there I changed the bindings to use the correct, un-namespaced lower cased, class name. Then I called this getResults() function in the get() function of the MyMorphMany class.
I used $query->getBindings() and $query->setBindings() to correct the bindings.
Hope this saves someone else a few days of work, like it would have saved me :)

Weird behavior of Red5 service parameters called from Actionscript

I have a Red5 service function that receives a single string as a parameter, and another function that takes no parameters, like the code below:
public class AService
{
private String someName;
public void setName(String aName)
{
someName = aName;
}
.
.
public String makeMessage()
{
return("Hello, "+someName);
}
.
.
other functions
}
I also have an ActionScript function that calls the service function, using the dynamic parameter:
public class Connector
{
private var netConn: NetConnection;
public function invokeCall(theFunc:String,...theParams): void
{
var resp:Responder = new Responder(checkResult);
netConn.call(theFunc,resp,theParams);
}
.
.
}
I am aware that the "...theParams" is actually an array of parameter objects. I also know that the NetConnector class' call() method uses that parameter object array. Unfortunately, when I do an invokeCall() on my service's makeMessage() method (without putting in a parameter) like so:
invokeCall("AService.makeMethod");
I get a function nonexistent message from Red5. The only way I can make it work is to create two invoke methods, one with parameters and one without, and call that function without parameters.
Furthermore, calling my setName() function, like so:
invokeCallwithPrams("AService.setName","factor3");
doesn't seem to work unless I change the signature of my service function:
public class AService
{
private String someName;
public void setName(String[] aName)
{
someName = aName[0];
}
.
.
public String makeMessage()
{
return("Hello, "+someName);
}
.
.
other functions
}
which I don't mind (even though the Red5 documentation indicates that I shouldn't have to treat the parameter as an array), except that when I pass the string "factor3" into the NetConnection class' call() method, somehow it becomes "[factor3]" in setName()!
Obviously, something is screwy here, but I haven't been able to figure it out.
I am using Red5 Version 1.0.1 and my Actionscript is Version 3.
Can anyone explain to me what is going on and (more importantly) how to fix this???
If so, please advise...
UPDATE: The weirdness continues
I did a test in which I changed the parameter of the function I used to set up and invoke the NetConnection class' call() method. Instead of passing it a "...theParams", I changed it to theParams:String, like so:
public function invokeCall(theFunc:String,theParams:String): void
{
var resp:Responder = new Responder(checkResult);
netConn.call(theFunc,resp,theParams);
}
Interestingly, the brackets that appear in my service method setName() go away!
Whatever this problem is, it has something to do with the dynamic parameters in Actionscript. I suspect that I have found a bug in Actionscript 3 that does not allow it to properly handle dynamic parameters that are passed to a method from another method.
Has anyone else seen this problem? Is there any solution? The dynamic parameters are supposed to allow anyone to add parameters as necessary and make them any object that is necessary. Unfortunately, it doesn't look like you can use dynamic parameters passed from another method without them being screwed up.
This looks like a serious bug in Actionscript. Am I correct?
Someone please advise...
I found the solution. It is not a bug in Actionscript, it is a bit of strangeness in the language.
The basic information about the solution can be found here:
AS3 variable length argument expand to call another function with var length args
Based on what is there, I needed to do the following in the method I am using for invokeCallwithParams:
.
.
var conn:Connector = new Connector();
private function invokeCaller(fName:String,...cParams)
{
cParams.unshift(fName);
conn.invokeCall.apply(conn,cParams);
}
This eliminates the unnecessary brackets passed into my setName() service function, meaning that I can pass dynamic, variable length parameters from one method to another...