I am trying to figure out a big PHP Library and it isn't that well documented. I would like to know if there is a way to print out everything about the class. For example I am using the get_class_methods() function to print out the methods of that class and it prints out an area of just that class. I would like to see all the methods within the objects within that class as well. It would be nice to see the variables and everything else. This way I can print out everything and then use the browser's search to find stuff that I need. Is this possible, or is there a method out there that already does this? I'm not that well versed in PHP so if you can give me a function that would be awesome.
PHP has a built in library called Reflection that allows you to analyze classes and objects in intricate detail.
You can get all the methods in a class like so:
<?php
$class = new ReflectionClass('Apple');
$methods = $class->getMethods();
var_dump($methods);
For class properties (member variables):
<?php
$class = new ReflectionClass('Apple');
$properties = $class->getProperties();
var_dump($properties);
A good IDE will help you navigate through the code, start debugging sessions and inspect properties values in execution time.
I felt in love with PHPStorm some years ago, and still today it's my favourite IDE. It even has a Vim plugin which emulates vim =)
There is a Structure view on that IDE, which shows the, well :), code structure of a file. This means every property and method of the opened class file. There is a Project view which is like a directory browser too.
Second recommendation will be to install ack (http://www.beyondgrep.com). PHPStorm has a really efficient searching mechanism, but sometimes you just want to search the entire subdirectories of a project for a regular expression. It's a neat tool also.
My two cents. :)
Related
For my current project I have to parse data "dumps" (EEPROM HEX dumps from a microcontroller) (coming from a file or a SQL database) that have a different format depending on the version of the software in the controller. (The software version is also in the dump.)
Extracting the version works and I have a somewhat working version that works for 1 specific version (but I find the current version quite messy). Since there is some overlap the between the different versions.
The output of the code is a JSON array that is fed to angular that formats the data into a table so a user can start playing with the data. (the JSON is generated with json_encode, works great)
What I'm looking for is a nice (oop, if possible) solution what can extract the data from the different file versions without a lot of code copy-paste. The only solution I can think of right now would be class for the 1st version, and than do a copy-paste (and a little edit) to a new class the 2nd version (and so on).
A generic answer on how to do this is fine for me, however I'm trying to do this in PHP.
Start by making a base class and a child class for the first version (the following code may not have perfect syntax):
class DataDump {
// some kind of storage
protected $contents;
}
class FirstVersion extends DataDump {
}
Then as you are building the FirstVersion class, try to pay close attention to what you think might be common in all the versions and move that code down to the DataDump parent class.
class DataDump {
// some kind of storage
protected $contents;
public loadFile($filename) {
....code....
$this->contents = ...
}
public processHeader() {
}
}
class FirstVersion extends DataDump {
public loadFirstFile {
$this->loadFile(...);
$this->processHeader();
...some code specific to this version...
}
}
Then you can slowly build the parent class with the things that are common, and there is almost always parts of the code that are common (even if in small segments). As you build other child classes, you may find other logic that can be shared, so push it down to the parent, or perhaps there is a base method that some of the child classes override and others can just use the base method.
Sometimes, when you have a big mess to deal with, it is hard to see all the shared code upfront and how to best organize it in a sane way, and this process helps tremendously when you are stuck. Just start writing and you will begin to see the patterns among all the versions, even if just helper methods.
I'm trying to create a composer package & i understand the basic workflow like of creating composer.json, auto loading and creating classes under src directory.
There is one small programming misunderstanding i have is that almost all the other packages i'm reading has interfaces and a class implementing them. I don't understand need of interfaces in this context and why we need them. I have never used interface or i'm not sure if i understand its general use case. It would be nice if someone can help me understand it.
Beside the other question i had in context to composer is how do i test / run a composer project whilst i create it?
Beside this projects that i'm referring has a command directory inside src i don't understand significance of this or its use case too. I guess it has something to do with symfony php console command.
Also there is a bin directory at source, now how is that useful.
Sorry if i'm being naive here but i'm just trying to understand which components fall where and why is it like that. I couldn't find a composer tutorial online past creating composer.json
You are asking a lot of questions at once, but I'll try to at least address interfaces, since I believe that's the most important one.
Interfaces are mostly used with Dependency Injection. They define methods without actually caring how the methods are actually implemented. A class may depend on an interface instead of an actual (concrete) class, which allows an easy way to swap components. Below is an example of how one might use interfaces.
interface PostsInterface {
public function getPosts();
}
class JsonPostFetcher implements PostsInterface {
public function getPosts() {
// Load posts from JSON files here
}
}
class MySqlPostFetcher implement PostsInterface {
public function getPosts {
// Load posts from a MySQL database
}
}
class Blog {
public function __construct(PostsInterface $fetcher) {
// Load posts from either JSON or a database
// depending on which fetcher is provided
$posts = $fetcher->getPosts();
}
}
Using this method anyone can now write their own code to provide posts from an external API ApiPostFetcher, SQLite Database SqlitePostFetcher, Serialized PHP files SerializedPostFetcher etc. One could even write a DymmyPostFetcher that simply returns a pretermined array of posts that could be used for testing purposes. You can then use any implementation of PostsInterface in your blog like in the following example.
$fetcher = new JsonPostFetcher(); // You can provide different fetchers here.
$blog = new Blog($fetcher);
If you're unfamiliar with dependency injection, I highly recommend learning it, since it will be especially useful in writing modular code.
I am writing a PHP extension in C, and I would like to put the classes, functions, and variables I am creating in a namespace. I have not been able to find anything in the extension documentation regarding namespaces. To be clear, I want the equivalent of
namespace MyNamespace{
class MyClass{
}
}
but in a C extension. More specifically, I am looking for a function or macro in the Zend C API that allows me to assign a PHP namespace to a class or function I have written in C. Is this possible?
Putting a class in a namespace is very simple. Where normally you would initialize a class with
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "MyClass", my_class_methods);
instead write the second line as
INIT_CLASS_ENTRY(ce, "MyNamespace\\MyClass", my_class_methods);
The namespace does not need to be included in the method declarations or in the members of the my_class_methods array to properly match them with the class.
To use Namespaces in PHP extensions, you are basically just putting a prefix in front of the class or function name.
I'm not really a PHP internals developer, so the specifics are not entirely clear to me how this works, unfortunately there is very, very little information online that I could find about this as well (I really put Google through it's paces), and the article below is the best I could find.
However, it seems this article hints at the correct solution, which seems to be, that when you register the function with the Zend engine/PHP internals, you do so like "myNS\\MyFunc" and it should then be accessible from the myNS defined there. I would try out a few different variations with this, and see how far that gets you.
Your best option would be to ask in #php-internals on Freenode (if you can get an invitation) or on the PHP Mailing list.
If you manage to find a solution, the Internet seems to be in need of a good article on how one would accomplish this.
Source http://www.php-cpp.com/documentation/namespaces
A namespace is nothing else than a class or function prefix. If you want your classes or functions to appear in a specific namespace, you simply have to add a prefix to the class or function name....
Update: I've updated my answer to try to be more clear. I'm sorry it took so long, I originally replied from my Phone while I was traveling, with every intention of coming back and responding to your original comment, but I genuinely forgot about it until I got a notification from SO about comments. My apologies.
Context
I recently inherited the development and maintenance of a well-programmed PHP application (sarcasm). The application is based on a commercial software (which I will not name), and there is a layer of customization (ours) that is built on top of it.
Unfortunately, this application uses a ton of globals and singletons (pun-intended). I have built test cases for all the things we've overridden. However, a lot of things relies on some global state of something, which can cause race conditions and all sorts of weird stuff.
Randomizing the tests
In order to catch most of these weird-o-tons (I like to call them that), I have built a PHPUnit TestDecorator, [as documented in the manual][1]. This one:
class PHPUnit_Extensions_Randomizer extends PHPUnit_Extensions_TestDecorator
{
public function __construct(PHPUnit_Framework_Test $test)
{
$tests = $test->tests();
$shuffle = array();
foreach ($tests as $t) {
if ($t instanceof PHPUnit_Framework_TestSuite) {
$shuffle = array_merge($shuffle, $t->tests());
} else {
$shuffle[] = $t;
}
}
shuffle($shuffle);
$suite = new PHPUnit_Framework_TestSuite();
foreach ($shuffle as $t) $suite->addTest($t);
parent::__construct($suite);
}
}
It basically randomizes the tests order to make sure a test doesn't depend on a global state that may or may not be correct.
The question
The problem arose when came the time to test my custom decorator. I have not found anywhere in the manual, Google, or Stack Overflow how to load it.
When analyzing the code, I saw that PHPUnit itself was instantiating the RepeatedTest decorator in the TextUI_TestRunner::doRun() method. I know I can subclass the TestRunner, override doRun(), arrange for my decorator to be created and then just call the parent::doRun() with my decorator instance as the argument, override TextUI_Command and create a new CLI script to use my stuff instead of the built-in stuff.
Before I (re-)invent the wheel, I was just wondering, is it possible do load a custom decorator without subclassing the TestRunner?
Thanks.
With current PHPUnit Versions there is no easy way to plug in in your own code for the most part. The only thing that offers interchangeability is the TestRunner and what you described makes sense to me.
I'm not aware of any other way to provide test decorators or change out most of the other classes phpunit uses.
The way you want to change the test execution order seems to work out even so I'm not sure how well it would shuffle suits.
Another way to achieve this thats maybe less hassle would be to create a subclass of PHPUnit_Framework_TestSuite randomly addTest your code.
If that doesn't work out another option would be to use the xml configuration file and build the test suite from <file> tags and before every execution have some code shuffle those tags. Afaik phpunit doesn't sort them in any way so execution will be random
Are you looking to see if every tests on its on really works and want to find interdependent tests?
Or do you really want to see if something breaks horribly when you do a lot of stuff that should not change anything in the wrong order?
I'm asking just in case you haven't considered --process-isolation yet. (Which i assume you have but asking isn't going to hurt and might save you some time and effort :) )
When you run every test with a fresh set of globals you will at least find all test interdependencies and thats just one cli switch away to make sure every test in your suite works fine on its own.
PHP's __autoload() (documentation) is pretty interesting to me. Here's how it works:
You try to use a class, like new Toast_Mitten()(footnote1)
The class hasn't been loaded into memory. PHP pulls back its fist to sock you with an error.
It pauses. "Wait," it says. "There's an __autoload() function defined." It runs it.
In that function, you have somehow mapped the string Toast_Mitten to classes/toast_mitten.php and told it to require that file. It does.
Now the class is in memory and your program keeps running.
Memory benefit: you only load the classes you need. Terseness benefit: you can stop including so many files everywhere and just include your autoloader.
Things get particularly interesting if
1) Your __autoload() has an automatic way of determining the file path and name from the class name. For instance, maybe all your classes are in classes/ and Toast_Mitten will be in classes/toast_mitten.php. Or maybe you name classes like Animal_Mammal_Weasel, which will be in classes/animal/mammal/animal_mammal_weasel.php.
2) You use a factory method to get instances of your class.
$Mitten = Mitten::factory('toast');
The Mitten::factory method can say to itself, "let's see, do I have a subclass called Toast_Mitten()? If so, I'll return that; if not, I'll just return a generic instance of myself - a standard mitten. Oh, look! __autoload() tells me there is a special class for toast. OK, here's an instance!"
Therefore, you can start out using a generic mitten throughout your code, and when the day comes that you need special behavior for toast, you just create that class and bam! - your code is using it.
My question is twofold:
(Fact) Do other languages have similar constructs? I see that Ruby has an autoload, but it seems that you have to specify in a given script which classes you expect to use it on.
(Opinion) Is this too magical? If your favorite language doesn't do this, do you think, "hey nifty, we should have that" or "man I'm glad Language X isn't that sloppy?"
1 My apologies to non-native English speakers. This is a small joke. There is no such thing as a "toast mitten," as far as I know. If there were, it would be a mitten for picking up hot toast. Perhaps you have toast mittens in your own country?
Both Ruby and PHP get it from AUTOLOAD in Perl.
http://perldoc.perl.org/perltoot.html#AUTOLOAD:-Proxy-Methods
http://perldoc.perl.org/AutoLoader.html
Note that the AutoLoader module is a set of helpers for common tasks using the AUTOLOAD functionality.
Do not use __autoload(). It's a global thing so, by definition, it's somewhat evil. Instead, use spl_autoload_register() to register yet another autoloader to your system. This allows you to use several autoloaders, what is pretty common practice.
Respect existing conventions. Every part of namespaced class name is a directory, so new MyProject\IO\FileReader(); should be in MyProject/IO/FileReader.php file.
Magic is evil!
The Mitten::factory method can say to itself, "let's see, do I have a subclass called Toast_Mitten()? If so, I'll return that; if not, I'll just return a generic instance of myself - a standard mitten. Oh, look! __autoload() tells me there is a special class for toast. OK, here's an instance!"
Rather such tricky code, use simple and verbose one:
try {
$mitten = new ToastMitten();
// or $mitten = Mitten::factory('toast');
} catch (ClassNotFoundException $cnfe) {
$mitten = new BaseMitten();
}
I think this feature comes in very handy, and I have not seen any features like it else where. Nor have I needed these features else where.
Java has something similar. It's called a ClassLoader. Probably other languages too, but they stick with some default implementation.
And, while we're at this. It would have been nice if __autoload loaded any type of symbols, not just classes: constants, functions and classes.
See Ruby's Module#const_missing
I just learned this: Ruby has a method on Module called const_missing that gets called if you call Foo::Bar and Bar isn't in memory yet (although I suppose that Foo has to be in memory).
This example in ruby-doc.org shows a way to use that to implement an autoloader for that module. This is in fact what Rails uses to load new ActiveRecord model classes, according to "Eloquent Ruby" by Russ Olsen (Chapter 21, "Use method_missing for flexible error handling", which also covers const_missing).
It's able to do this because of the "convention over configuration" mindset: if you reference a model called ToastMitten, if it exists, it will be in app/models/toast_mitten.rb. If you could put that model any place you wanted, Rails wouldn't know where to look for it. Even if you're not using Rails, this example, and point #1 in my question, shows how useful it can be to follow conventions, even if you create them yourself.