symfony can't load a class with classname set dynamically - symfony

I create a service in symfony 3.2
I want to call a different class set by a parameter
public function setPaymentMethod($paymentMethod){
$this->datas = $paymentMethod->getDatas();
$className = ucfirst($this->datas["MODULE_NAME"]);
new $className($this->datas);
}
In this case the code try to load the class Spplus which is defined in my service with a use statement
I get this error:
Attempted to load class "Spplus" from the global namespace.
Did you forget a "use" statement?
If I try to load "manually" Spplus class it works
public function setPaymentMethod($paymentMethod){
$this->datas = $paymentMethod->getDatas();
new Spplus($this->datas)
}

As said by Cerad It works with a fully qualified classname.
public function setPaymentMethod($paymentMethod,$order){
$this->datas = $paymentMethod->getDatas();
$className = "SiteBundle\\Service\\PaymentMethod\\" . ucfirst($this->datas["MODULE_NAME"]);
$this->paymentMethod = new $className($this->datas,$order,$this->rootDir);
}

Related

dynamic class loading - Attempted to load class _CLASS_ from namespace _NAMESPACE_

So i try to load a class inside a service in Symfony4.
It doesn't matter if i load it as classname or as App\to\class\name\classname.
It generates the same error.
Other posts said you need to add the whole fully qualified classname..
This doesn't work. Am I missing something?
Code below:
<?php
// src/Service/AdwordsService.php
namespace App\Service;
use App\Service\AdTypes\ExpendedTextAdTypes as ExpendedTextAdTypes;
class AdwordsService{
...
public function getAdsModel($ad) //<-- for example "EXPANDED_TEXT_AD"
{
$type = explode('_',strtolower($ad->getType()));
$modelName = array_map('ucfirst', $type);
$modelName = implode('',$modelName).'Types';
// will load ExpandedTextAdTypes
return new $modelName($ad);
}
...
}
Class that it tries to load:
<?php
// src/Service/AdTypes/ExpendedTextAdTypes.php
namespace App\Service\AdTypes;
class ExpendedTextAdTypes
{
private $adData;
public function __construct($ad)
{
$this->adData = $ad;
}
}
The ultimate problem(s) was a simple typo: EXPANDED_TEXT_AD vs EXPENDED_TEXT_AD
along with the need to use a fully qualified class name:
// No need for any use statements
// use App\Service\AdTypes\ExpendedTextAdTypes as ExpendedTextAdTypes;
public function getAdsModel($ad) //<-- for example "EXPENDED_TEXT_AD"
{
$type = explode('_',strtolower($ad));
$modelName = array_map('ucfirst', $type);
$modelName = implode('',$modelName).'Types';
$modelName = 'App\\Service\\AdTypes\\' . $modelName; // Add this
return new $modelName($ad);
}
As a rule, typo questions are considered to be off-topic. But this question actually has two issues as well as pointing out that the use statement is not needed. So I guess it can qualify as an answer.
The question's title is also misleading. I clicked on the question because I had never seen CLASS in an error message. It would have been better to have posted the actual error message thus possible making it easier to detect the typo.
And finally, a bit of unsolicited advice. This sort of transformation from EXPENDED_TEXT_AD to ExpendedTextAdTypes can be difficult to maintain and definitely locks you in to a class naming scheme. Why not just use ExpendedTextAd instead of EXPENDED_TEXT_AD? Symfony does this sort of thing all the time.

alternatives of controller method

I am using this code in my laravel 5.3 project but it says that it is badcallmethodexception , I found that controller method is no longer available in new version , how to write this code?
this is my code:
Route::controller('notifications', 'NotificationController');
inside this controller there is this code:
public function getIndex()
{
return view('notification');
}
public function postNotify(Request $request)
{
$notifyText = e($request->input('notify_text'));
}
If you are not using default laravel controller methods you need to define which method should be called for route.
Route::get('notifications', 'NotificationController#getIndex');
Route::post('notifications', 'NotificationController#postNotify');
Write route as :
Route::post('notification','NotificationController#method-name');
Here post is method type that you can use as per your requirement. or else you can use resource as
Route::resource('notification','NotificationController');
Resource can be used only for index,create,store,update and destroy method.
Laravel document : https://laravel.com/docs/5.3/controllers#resource-controllers

How to reference a class in ASP.NET

I created a website and would like to have a class to centralize all the code that I use frequently in the entire project, for instance, a method to connect to the database. Question: after I create this class, on the App_Code folder, how can I use it in the aspx.cs pages? I mean, should a reference it? Should I inform add a namespace?
Thanks!
Create the class file as public and you will be able to access the class file at any part of your project.
namespace applicationName
{
public class DataManager
{
public static DataTable GetData(StringBuilder sql)
{
}
}
}
you can access the DataManager from your code.
DataManager.GetData(SQL);
Yes, put your class in a namespace and consider making the class static if possible, that way it can be used in code throughout your project without instantiating the class. This is common for utility classes that pass in objects and do work with them, but do not need the actual utility method to be part of a class instance.
For example:
namespace My.Utilities
{
public class static ConnectionStringHelper
{
public static string GetConnectionString()
{
// Logic here to actually get connection string
return yourConnectionString;
}
}
}
Now, code in your project just needs to reference the My.Utilities namespace and then can use the GetConnectionString() method, like this:
using My.Utilities;
string connString = ConnectionStringHelper.GetConnectionString();
You can do it a number of ways. Technically you can drop the namespace completely and your code becomes a free for all (accessible from anywhere naturally). I prefer to use namespaces personally, but I have seem people just avoid them.
If your class Foo is in Some.Namespace, you can reference it as such:
Way one:
Some.Namespace.Foo foo = new Some.Namespace.Foo()
Way two: Use the "Use" command
If your class is inside of Some.Namespace and you don't want all the junk preceding your class name, you can add:
using Some.Namespace;
to the top of your file.
I may be miss understanding what you are saying. If you are talking about setup, you can make a centralized class that manages everything. This class can be a singliton. For instance:
class MyClass
{
public static MyClas Singliton;
static MyClass()
{
Singliton = new MyClass();
}
public void someFunction()
{
}
}
This will create and manage a single reference to your class so that everything is managed out of there (hence being called a "singleton"). As a result, you can access it by:
MyClass.Singliton.someFunction();
There are ways to protect your singliton instance from being overwritten, but this is the basic idea. If you want to manage stuff out of a single location without recreating classes, singletons are the way!
http://msdn.microsoft.com/en-us/library/ff650316.aspx
If the class is wrapped in a namespace, then yes, you'll need a using statement that matches your namespace. For instance, if your class is wrapped in a namespace like so:
namespace My.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
then anywhere you want to use that class you'll need to add
using My.Namespace;
to the top of the files where you want to utilize the class(es) you've defined. Then you can use your class as you would expect:
Foo foo = new Foo(); //for a new instance
Foo.Bar(); //for a static method
This is, of course, assuming that the class is in the same assembly and you don't want to mess with adding it to the GAC.
Alternatively, if for some reason you don't to use a using statement you can use the fully qualified name of the class:
My.Namespace.Foo foo = new My.Namespace.Foo(); //for a new instance
My.Namespace.Foo.Bar(); //for a static method
This is most useful if you have namespaces that conflict, for instance if you had
namespace My.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
somewhere, and
namespace MyOther.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
somewhere else, but needed to use them both in the same scope.

Using reflection in PHPUnit

I'm testing a private method of a class used in Symfony2 project with PHPUnit.
I'm using the private methods testing strategy (through reflection) described by many developers such as http://aaronsaray.com/blog/2011/08/16/testing-protected-and-private-attributes-and-methods-using-phpunit/
But unfortunately, I got the following error:
There was 1 error: 1) My\CalendarBundle\Tests\Calendar\CalendarTest::testCalculateDaysPreviousMonth
ReflectionException: Class Calendar does not exist /Library/WebServer/Documents/calendar/src/My/CalendarBundle/Tests/Calendar/CalendarTest.php:47
<?php
namespace My\CalendarBundle\Tests\Calendar;
use My\CalendarBundle\Calendar\Calendar;
class CalendarTest
{
//this method works fine
public function testGetNextYear()
{
$this->calendar = new Calendar('12', '2012', $this->get('translator'));
$result = $this->calendar->getNextYear();
$this->assertEquals(2013, $result);
}
public function testCalculateDaysPreviousMonth()
{
$reflectionCalendar = new \ReflectionClass('Calendar'); //this is the line
$method = $reflectionCalendar->getMethod('calculateDaysPreviousMonth');
$method->setAccessible(true);
$this->assertEquals(5, $method->invokeArgs($this->calendar, array()));
}
}
Why?
Thank you in advance
You need to use the whole namespaced class name when creating your reflection method, even if you include a use statement.
new \ReflectionClass('My\CalendarBundle\Calendar\Calendar');
This is because you are passing the class name as a string to the constructor, so it doesn't know about your use statement and is looking for the class name in the global namespace.
Also, for what it's worth, you don't actually need to create a ReflectionClass, then call getMethod() on it. Rather, you can directly create a ReflectionMethod object.
new \ReflectionMethod('My\CalendarBundle\Calendar\Calendar', 'calculateDaysPreviousMonth');
That should be essentially the same, but a bit shorter.

use actionscript file in flex library

i want make own flex library and in this library use own actionscript file which will i use in more component in this library..this file contents eg only code
public function computeSum(a:Number, b:Number):Number {
return a + b;
}
but when i can this create just when i click File-New-Actionscript File (filename - OK) is in Problem view Error: A file found in a source-path must have an externally visible definition. If a definition in the file is meant to be externally visible, please put the definition in a package
thanks for help
You should encapsulate it on class, in order to use it with import directive, else u could use it with include
Another approach is to create a "helper" class, or so called "singleton" class.
- a class having only 1 instance, created statically.
on this class u can expose the library functions which u do need and use them everywhere.
package
{
public class Singleton
{
private static var singleton : Singleton
public static function getInstance() : Singleton
{
if ( singleton == null )
singleton = new Singleton();
return singleton;
}
public function Singleton()
{
}
public function visibleTroughtTheSingletonfunction( arg1 : int ... ) : void
{
}
public static function directlyVisiable() : void
{
}
}
}
the accessing the singleton would be something like :
Singleton.getInstance.visibleTroughtTheSingletonfunction( 1 );
OR
Singleton.directlyVisiable();
depending on your needs.
Well first you'll need to create a class (and a package) and put that method inside that (not just into an empty AS file) and second if you want to be able to access the method without creating an instance of the class make this method static.
If you don't need to change the class file during runtime then make action class compile into swc library.
create a Action script project and compile it in the bin folder you found the .swc library file. include that .swc into your project .

Resources