annotations,inject,php-di , PHP-DI annotation not working


PHP-DI annotation not working

Question:

Tag: annotations,inject,php-di

I have installed php-di 4.4 in a new custom project using composer.Im runing a xampp localhost with php 5.6.3 but I set netbeans for php 5.4 on this project. Im new to php-di, I did use annotations in my android projects but cant seem to make it work here. The code is simple, im testing out the injection to see how it works, here is the code:

// composer autoload
require_once __DIR__ . '/vendor/autoload.php';

// injection entry point
$builder = new DI\ContainerBuilder();
$container = $builder->build();

class ClassA
{
    public function methodA()
    {
        echo 'methodA';
    }
}
class ClassB
{
    /**
     * @Inject
     * @var ClassA
     */
    public $param;

    public function methodB()
    {
        $this->param->methodA();
    }
}

$b = new ClassB();
$b->methodB();

this is the error that i get: Call to a member function methodA() on null in D:\Projects\profi\test.php on line 27

It's basic implementation I don't understand why it does not inject.

Thank you in advance.


Answer:

PHP-DI cannot magically intercept when you create B (to inject A in B). You have to create B using PHP-DI:

$b = $container->get('ClassB');
$b->methodB();

Related:


Annotations to detect method calls with wrong order of String parameters


java,intellij-idea,annotations,code-inspection
We have a big application which uses a lot of Strings: for serial numbers for product names for order number for customer references ... and many more ... Unfortunately our developers are only human. Sometimes the String values get mixed up when calling methods. For example: // this method public...

How to map multiple One-to-Many association in Hibernate


java,hibernate,annotations,one-to-many
I have these 3 tables in my database CREATE TABLE IF NOT EXISTS `User`( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) CREATE TABLE IF NOT EXISTS `Project` ( `id` INT NOT NULL AUTO_INCREMENT, `manager` INT NOT NULL, `name` VARCHAR(255) NOT NULL DEFAULT...

Pros and cons of using type annotations in Swift


ios,swift,annotations
I was wondering the difference of using and not using type annotations(var a: Int = 1 vs var a = 1) in Swift, so I read Apple's The Swift Programming Language. However, it only says: You can provide a type annotation when you declare a constant or variable, to be...

Symfony2 Annotation Inheritance


php,symfony2,annotations
In my project, I have a BaseController class which implements several methods used by all of my controllers. Now I wanted to add @QueryParam for that base class. My class looks like this: class DoctrineRESTQueryController extends FOSRestController { /** * @QueryParam(name="start",default=0) * @QueryParam(name="limit",default=null) */ public function getQueryResponseAction (ParamFetcher $paramFetcher) {...

can't inject Providers mock in JerseyTest


java,mocking,jersey,integration-testing,inject
I'm getting Providers from context in my filter to get defined ObjectMapper public class Filter implements ContainerRequestFilter, ContainerResponseFilter { @Context private Providers providers; @Context private HttpServletRequest request; private ObjectMapper getObjectMapper() { ContextResolver<ObjectMapper> contextResolver = providers.getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE); if (contextResolver == null) { return new ObjectMapper(); } return contextResolver.getContext(null); } } but...

Java custom annotation to find methods


java,annotations
I want to create annotation (for which I can set some kind of id), which I can put on variable, and write method which return getter or setter method of this variable by annotations setted id; As example I made something like that but only for method, so I need...

How to inject a Map using the @Value Spring Annotation?


java,spring,dependency-injection,annotations,spring-annotations
How can i inject values into a Map from the properties file using the @Value annotation in Spring ? My Spring Java class is and i tried using the $ but, got the following error message Could not autowire field: private java.util.Map Test.standard; nested exception is java.lang.IllegalArgumentException: Could not resolve...

Python - Add annotation in subplot imshow


python,matplotlib,annotations,imshow
I would like to add some annotations on a figure with multiple subplots...On the figure below i would like to write something below the 2 right figures and at the left top. How can i do that? I try with : ax3.text(0.1, 0.5, '$\sigma =$' resV.mean(), size=12, ha='center', va='center') But...

Update custom annotation pin image to standard annotation pin in swift


ios,swift,annotations,mapkit,coordinates
I want to update map view every 60 seconds & make an annotation with custom pin/image but want to show standard pin [red color - See Figure 6-1] icon to the previously drawn annotation. I tried like below code but that does not working properly. With another custom image it...

why spring 4 recommend annotation rather than configuration file? [closed]


java,spring,configuration,annotations
Recently I'm learning the spring framework of java. I am curious that why spring 4 recommend annotation to set up spring rather using configuration file? Some people said that the spring configuration file is too complicated. But I think using annotation is going to the opposite direction of purpose of...

In a JUnit test is there a rule to set the subject of the test


java,junit,annotations
I've been writing a lot of JUnit tests lately and see this same boilerplate pattern. public class MathOpTest { private MathOp a; @Before public void setUp(){ a = new MathOp(); } ... } Is there an annotation to set this up for me as I always need to write a...

PHP-DI annotation not working


annotations,inject,php-di
I have installed php-di 4.4 in a new custom project using composer.Im runing a xampp localhost with php 5.6.3 but I set netbeans for php 5.4 on this project. Im new to php-di, I did use annotations in my android projects but cant seem to make it work here. The...

How to add Coordinates to CLLocationCoordinate2D from Dynamic NSMutableArray?


ios,objective-c,annotations,nsmutablearray,mkmapview
I have a MapView in which I would like to add annotations and a route from defined coordinates that I add from a Textfield and store in an NSMutableArray. Now I'm able to show the route from multiple coordinates but only when I insert them in my code as follow...

How to automatically format PHP annotations in PHPStorm


php,annotations,phpstorm,swagger-php
I'm working with a large number of files that have PHP block docs with Swagger PHP annotations on them, however they are not indented. Is there anyway to automatically format them with spaces? Turning /** * @SWG\Api( * path="/building/{buildingId}", * @SWG\Operation( * method="GET", * type="Building", * summary="Returns a Building object...

Annotator dependencies: UIMA Type Capabilities?


java,annotations,nlp,uima,dkpro-core
In my UIMA application, I have some annotators that must run after a certain annotator has run. At first, I thought about aggregating these annotators together, but I have other annotators that are also dependent on this (and other) annotator, which makes aggregating hard and/or unpractical. I read about Type...

Representation of inner source-retained annotation


java,annotations,annotation-processing
We have this class: public class MyClass { @Retention(RetentionPolicy.SOURCE) private @interface MyInterface { } @MyInterface public void hello() { } } As you can see, it has an inner, source-only annotation. My question is: should the exported binary (jar) contain the MyClass$MyInterface.class file or not? If we look at the...

How to get @interface parameter in jersey WriterInterceptor Implementation


java,annotations,jersey,jax-rs,interceptor
I have an interface, for example @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface AutoLogged { boolean query() default false; } How can I get query parameter in interceptor implementation? @Provider @AutoLogged public class AutoLoggedInterceptor implements WriterInterceptor { @Context private ResourceInfo resourceInfo; @Override public void aroundWriteTo(final WriterInterceptorContext context) throws IOException, WebApplicationException { try {...

How can I specify the type of the field that an Annotation should be applied to in Java?


java,android,reflection,annotations
I'm creating a simple annotation, to help me inflating settings inside my Android application. The annotation is this: @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface CoreSettings { String name() default ""; } I want to ensure it will only be used in fields which type extends a custom class named BaseSettings. In the...

Filter array based on coordinate from mapview frame in objective C


ios,objective-c,xcode,annotations,mkmapview
I have hundred's of map annotation. Annotation are from array of dictionary with lat and long val same data shown in table view. Table view and map view are same view based on screenheight/2. What I need for example in my array have 100 lat and long value table view...

spring data mongodb find by collection


mongodb,spring-mvc,annotations,spring-data-mongodb
I am using spring-data-mongodb. Here is my controller method: Controller: @RequestMapping(value = "/getByCategory",method = RequestMethod.GET, consumes=MediaType.APPLICATION_JSON, produces=MediaType.APPLICATION_JSON) public Iterable<Node> getByCategory(@RequestParam(value="categories") List<String> categories) throws EntityNotFoundException { Iterable<Node> nodes = nodeService.getByCategory(categories); return nodes; } Here I am passing list of string as a request parameter. My service method is: public Iterable<Node>...

Python anotation arrow direction


python,python-2.7,matplotlib,annotations
I am trying to annotate a scatter plot in Python 2.7, with Matplotlib. Here is the plot code: import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(5,3), columns=list('ABC')) df.insert(0,'Annotation_Text',['ABC','DEF','GHI','JKL','mnop']) q = 2 pqr = 1 # Scatter Plot: x = df['A'] y = df.iloc[:,q]...

Angular is giving me an injection unresolved error, but my controller isn't asking for any injections


javascript,angularjs,controller,modal-dialog,inject
I have a modal controller that is buggy, so I've been commenting out code to try to figure out the bug. Currently, my modal HTML partial is an empty div tag and my controller is a single console.log, with no arguments or parameters. The $modal.open call only specifies the controller...

Dynamic annotation/attribute values


c#,validation,annotations,attributes
I run into a problem using data annotations in c#. I am using custom required and range attributes and I want to set an object as the error message. [MyOwnRequired(ErrorCode=GlobalMessages.Message01] public string Description { get; set; } The problem is that I do have a class holding several objects (GlobalMessages.Message01,...

What should I annotate when I unit test the GPS function with Robolectric?


unit-testing,annotations,robolectric
I am referring the following site http://googletesting.blogspot.ca/2010/12/test-sizes.html . There it was mentioned that we should annotate @LargeTest if our test method is accessing the network feature. I am using Roboloectric for unit testing. And my method uses the shadowLocationManager to simulate the GPS location. I am not sure what should...

Map with accumulator on an array


ruby,inject
I'm looking to create a method for Enumerable that does map and inject at the same time. For example, calling it map_with_accumulator, [1,2,3,4].map_with_accumulator(:+) # => [1, 3, 6, 10] or for strings ['a','b','c','d'].map_with_accumulator {|acc,el| acc + '_' + el} # => ['a','a_b','a_b_c','a_b_c_d'] I fail to get a solution working. I...

Symfony2 / Doctrine2 : how to access an entity annotation mapping?


symfony2,doctrine2,annotations,mapping,accessor
In my Symfony2/doctrine2 application, I have two entities, Media and Recipe. They can be linked by a oneToMany or a ManyToMany association. In the case of a oneToMany relationship, I am using the following code to retrieve the Recipe linked to an instance of Media : $accessor = PropertyAccess::createPropertyAccessor(); $reflect...

Ambiguous mapping found when I use extends clause


java,spring-mvc,inheritance,annotations
I have a CustomerController and CustomerCardController classes that extend CrudMethods class. I choose so, because these two controller use the same methods (getFileCustomer() is one of these). And I thought that it had been better use the inheritance to save code's rows. CustomerController @Controller public class CustomerController extends CrudMethods {...

Symfony2 AnnotationException You have to enable OPCache or ZendOptimizer


symfony2,doctrine2,annotations,doctrine,opcache
I have application based on the Symfony2 framework. I have moved to the production environment, website was running fine (I was trying to adjust caching - on my hosting is xcache). But suddenly I has this error: Fatal error: Uncaught exception 'Doctrine\Common\Annotations\AnnotationException' with message 'You have to enable opcache.save_comments=1 or...

How to define an annotation for more than one target in Groovy?


groovy,annotations
In Java, to define an annotation for more than one target, the curly braces can be used: @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD}) public @interface AnnotExample { String name(); } However, this doesn't work in Groovy: $ groovyc AnnotExample.groovy org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: AnnotExample.groovy: 8: expecting '}', found ',' @ line 8, column 26....

Groovy multiple Delegate annotation/Wrapper for list


list,groovy,delegates,annotations
I'm struggling how to use the @Delegate annotation in Groovy. What I'm trying to achieve is the following. I have two types of items (itemA & itemB). ItemB basically consists of a list of itemA's, so I used the @Delegate annotation. Furthermore, multiple itemA's are stored in a collection (collectionA),...

Read controllers custom annotations from a custom Command in Symfony 2


php,symfony2,annotations
I have created custom annotations to generate JSON files (for NodeRed if you ask...) and i'm testing them successfully from a dummy method in a dummy controller. I would like to port all that to a custom Sf command whose job would be to read all Controllers annotations in my...

How to get full return type forwarding in Xtend's Active Annotations?


java,android,annotations,xtend
I'm trying out Xtend's Active Annotations by writing a simple "Logged" annotation for tracing when methods have been called. Basically I want to write this in Xtend: @Logged override onCreate() { sampleFuncCall() } and get something like this in Java: @Override void onCreate() { Log.d("TAG", "onCreate started"); sampleFuncCall(); Log.d("TAG", "onCreate...

@PathVariable and @RequestParam not working together


spring,spring-mvc,annotations,spring-annotations,path-variables
I have below code in my controller: @RequestMapping(value = "/child/{nodeId}/{relType}",method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON) public Iterable<Node> getConnectedNodes(@RequestParam("page")int page, @RequestParam("size")int size, @PathVariable("nodeId") String nodeId, @PathVariable("relType") String relType) { return nodeService.getConnectedNodes(nodeId, relType,page,size); } And this is the API url i am hitting...

How to implement a parameter decorator in TypeScript?


annotations,typescript,decorator
I've been trying to use a parameter decorator @logParameter: class Person { public name: string; public surname: string; constructor(name : string, surname : string) { this.name = name; this.surname = surname; } public saySomethingAsync(something: string, @logParameter cb: (said : string) => void) { cb(this.name + " " + this.surname +...

Specify user handlers for JAX-RS when using annotation scanning


rest,annotations,websphere-liberty,apache-wink
How to specify user handlers for JAX-RS when using annotation scanning? I am following this link and have created my custom handlers. I have annotated my Application subclass as: @ApplicationPath("rest") public class RestfulResourceLoader extends Application { } so that I don't have to entry in web.xml file. What I am...

Load different Entities from a single table with a column as discriminator


java,database,spring,hibernate,annotations
I have the following table with 3 types of people, boy, man and woman: CREATE TABLE IF NOT EXISTS person( id int unsigned NOT NULL AUTO_INCREMENT, type VARCHAR(100), name VARCHAR(100), description VARCHAR(2000), PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO person (id, type, name, description) VALUES(1, 'child', 'Omar', '');...

Read annotation of generic class Java


java,generics,annotations
I had an idea to use a Dao class (Dao.java): class Dao <Model extends AbstractModel> { public String getUrl() { return Model.class.getAnnotation(MyPath.class).url(); } } and a model like this (Account.java): @MyPath(url = "blabla") class Account extends AbstractModel { ... } but the problem is that in that case if i...

Technical debt on custom web rule in sonarqube 5.1


web,annotations,sonarqube,sonar-runner,sonarqube-5.0
I am facing issue in technical debt with custom web rules. I have web plugin but no technical debt is assigned to rules. I want code or annotation through which i can assign some constat/issue value to each rule and can calculate debt from that. I used following anotations while...

android json data to spring mvc4


java,android,json,spring-mvc,annotations
I am new to using Spring mvc4 annotation . In all i want to do is using spring mvc as a web service . so i would be thankful if anyone could provide me a solution for it. My android code is as: HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000);...

Adding a pin annotation to a map view on a long press in swift


ios,swift,annotations,maps,mkmapview
I'm trying to make an iPhone app which requires users to be able to long press on a place on a map view to drop a pin there. Does anybody know how this is done? The behaviour is observable in apple maps when you long press on the screen. It...

Why must a setter be empty, if the property uses annotation attributes?


c#,annotations,setter
i want to use the setter to auto-correct the value and want to use the RequiredAttribute too. But in this case the RequiredAttribute do not work, because the setter is not empty. So, why have the setter to be empty? [Required(AllowEmptyStrings = false, ErrorMessage = "The Name cannot be empty....

Guice : Inject an ArrayList of Strings


java,arraylist,guice,inject
I'm trying to inject an ArrayList of Strings with the help of Guice. I want to show a panel with many RadioButtons (for example) where an user can select some services to activate. Once selected, I would like to get all the names of the selected services and add them...

spring-cassandra UDT data insert


java,annotations,cassandra,datastax-java-driver,spring-data-cassandra
Can someone help me to find out how to insert Cassandra UDT data using Spring POJO class? I created one POJO class to map Cassandra's Table and Created one another class for Cassandra UDT, but when i inserted main POJO class that map Cassandra's table than it's not recognized another...

Is there a way to enclose multiple event declarations on a single [] block?


events,f#,annotations
It is a little tedious to write: let e1 = Event<_>() let e... = Event<_>() let en = Event<_>() [<CLIEvent>] member this.E1 = e1.Publish [<CLIEvent>] member this.E... = e....Publish [<CLIEvent>] member this.En = en.Publish In the code, I show how I need to write n [<CLIEvent>], 1 for each event....

Animated annotation on WKInterfaceMap Watchkit


ios,animation,annotations,apple-watch,wkinterfacegroup
Is there anyway to have an animated annotation for WKInterfaceMap of Watchkit? I have 35 images to form the animation. Currently I am using a NSTimer which calls -(void)addAnnotation:(CLLocationCoordinate2D)location withImageNamed:(NSString *)name centerOffset:(CGPoint)offset method with a different image names but the result is not efficient and the animation is not smooth...

Get id column name from POJO, using reflection


java,jpa,reflection,annotations
@Entity @Table(name="MY_TABLE") public class MyTable{ @Id @Column(name="MY_TABLE_ID") @GeneratedValue(strategy = GenerationType.AUTO ,generator="SQ_MY_TABLE") @SequenceGenerator(name="SQ_MY_TABLE", sequenceName="SQ_MY_TABLE") private Long myTableId; How can I, using reflection, get the primary key column name from my POJO, defined with the javax.persistence.Id annotation? I'd have to find the @Id and then get the name property of the @Column...

Ruby inject until sum exceeds a set value and return the index where this occurs


arrays,ruby,inject
With the following array and value: v = 50 a = [10, 20, 25, 10, 15] I want to iterate through the array adding up the values until the sum of these values exceeds the variable v. And then I want to be able to return the index in the...

What is the correct CascadeType in @ManyToMany Hibernate annotation?


java,hibernate,annotations,many-to-many,cascade
I am trying to model a transient operations solution schema in Hibernate and I am unsure how to get the object graph and behavior I want from the model. The table structure uses a correlation table (many-to-many) to create lists of users for the operation: Operation OperationUsers Users op_id op_id...

How do I access parameters specified in a Java Aspect?


java,reflection,annotations,aop
I have an annotation called "@ProgressCheck" that we can put on a controller to check the progress of an application. If the application is already submitted or late, then it throws the user to a page appropriate for that situation. The annotation interface is: @Retention(RetentionPolicy.RUNTIME) public @interface ProgressCheck { }...