How to make sections of PHP code in eclipse - php

I've really only just discovered that you can use /** #blah */ comments to specify certain things, but is it possible to create sections in code?
Like:
/** Start Section "Blah" **/
$result = doSomething();
echo $result;
/** End Section "Blah" */

No PDT can't do that. Generally expandable code sections are identified by function and class method bodies.
If you think you need artificial sections identified by comments I recommend to rather think about reorganizing your code into more fine grained files, function, classes and methods that can be easily documented using PhpDoc (which is the standard PDT uses).

these sections
/**
* here goes your text
* #author Nanne
* /
Are based on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html
Look at this page where a documenter for PHP is described. I don't know what standard is used in Eclipse, but I'm guessing they're all rather alike:
http://www.phpdoc.org/
Is is mostly based on commenting certain parts of code, e.g. classes, functions and variables. As far as I know there is no special code for "sections". The reason I think this, is that you are 'supposed' to make a documentation from this, with classes, it's methods etc. There is no special way to represent "sections" in a documentation like that.
But do read above links, it'll clear up a lot!

In PHP you can use sections to separate pieces of code. Syntax is like this:
Blah:{
$result = doSomething();
echo $result;
}
These were used by goto style procedural programming before object oriented programming was used (classes and instances). Using these sections and goto statements is very bad practice and should be shunned by any developer.
https://www.php.net/manual/en/control-structures.goto.php

Related

Using proxy or shortcuts methods in PHP

I have classes with larges methods name that are called too many times.
Example:
/**
* This class do awesome things.
*/
class AwesomeClass {
/**
* Do something awesome.
*/
public function doSomethingAwesome()
{
//Do something awesome
}
}
Now, I call the method:
$awesomeInstance->doSomethingAwesome();
The method name is large and is typed to many times. For prevent misspelling, I created a shortcut method:
/**
* Shortcut of doSomethingAwesome()
*/
public function dsa()
{
return $this->doSomethingAwesome();
}
And calling method:
$awesomeInstance->dsa();
Is this a bad practice? How afect the performance?
It is a commonly stated rule of thumb that code is read more often than it is written. Even if writing code only for your own use, you will not remember everything about how it works when you read it back in 6 months time to make some amendment.
Your shortcut method names optimise your codebase for writing, because they make it quicker to type, and less error-prone.
However, they are actively harmful for reading, because they lead to less descriptive code, and require you to cross-reference the comment on the shortcut to check what it abbreviates.
Instead, you should aim to write the same code (thus retaining readability) but find tools to do so more easily and with fewer errors. A major helper in this case would be using a more powerful code editor or IDE, which will include auto-complete and code navigation facilities. You can also use standalone "code linting" / "static analysis" tools to pick up mistyped function names.
Performance shouldn't be an issue. But readability of your code suffers. You should use descriptive method names. If this function is called too many times it's a code smell and some refactoring may be needed.
I would not recommend creating shortcut methods. I am not sure why your methods do have such long names. Maybe your methods do more than one task?
for example:
$awesomeInstance->parseCheckAndSaveMyAwsomeObject();
in that case, you should write a dedicated method for each task.
Could you explain it in more detail?

PHP Debugging Classes - Print everything

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. :)

php annotations - minimal working example

Last time i checked (2008) annotations in php weren't so wide spread. Now after reading some material and having done some "googling", i am still a little confused. Could someone provide a minimal working example that illustrates how to use annotations in php:
Lets just say i want something like this to work:
class ClassName
{
/**
* #DefaultValue("test")
*/
public $prop;
}
// so that i can do
$kls = new ClassName();
$kls->prop // => test
I havent done php in a long while
UPDATE
The purpose of this question is to understand how libraries/frameworks like symfony,flow3 and doctrine implement their annotations.
Annotations are not (yet) supported by PHP. There is an RFC for a proposed implementation, but it's still unknown if or when would that happen.
The particular example that you've given might be interpreted by an IDE as a value to auto-complete and otherwise you can just do public $prop = 'Test';, but I guess you already know that and it's not your real intention.
In PHP Manual -> Function Reference Variable and Type Related Extensions -> Reflection, exists a method getDocComment() in several reflection classes (ReflectionClass, ReflectionMethod, ReflectionFunction, ReflectionFunctionAbstract, ReflectionProperty...) where you can get the doc comment block. Then process your comment the way you want. Example:
class Foo {
private $a;
private $b;
...
/**
* #annotation('baz')
*/
public function bar() {
...
}
}
$reflMethod = new ReflectionMethod('Foo', 'bar');
//prints
//string(26) "/**
// * #annotation('baz')
// */"
var_dump($reflMethod->getDocComment());
PHP Shouldn't support annotations, they're a scourge among PHP developers at the moment. They cause many problems:
They break version control. If you want two differently configured instances of an object in different projects they become different branches even though it's the configuration that's changed and not the logic.
They reduce portability. If you move a class around between two projects that use annotations, the annotations may break the second project
They break encapsulation. The application code shouldn't be concerned with how it will be used externally. Annotations tell the client code what it should be doing rather than letting the client code decide. In your #DefaultValue example, what if you use the class somewhere that isn't paying attention to the annotation? Will the class work anyway if the default value hasn't been set? Yes? No? Maybe? Whatever the answer, it's not clear in the API and there's no way to know whether the object, once constructed is ready to fulfil its responsibilities.
They limit flexibility. Using Symfony's #Inject as an example, it's impossible to create two instances of the class with different injected parameters .
See: Annotations are an abomination and PHP Annotations Are a Horrible Idea for a more detailed explanation of why they should be avoided.
PHP doesn't support annotations (yet).
The only place I've used annotations in PHP that affect code flow is in phpUnit, which supports a number of annotation markers (eg #DataProvider and #ExpectedException) for handling various aspects of the test script.
That works fairly well, but isn't handled by PHP natively; phpUnit has to parse the script itself before including it and running the code normally. Fair enough for a unit test script, but not an ideal solution for a production system.
So I think the real answer is that you'll have to wait until PHP implements annotations natively. I believe there's a proposal for it, but it certainly isn't going to happen any time soon -- it's definitely not going to be in 5.5, which will be released next year. I don't think there are any fixed plans for the features in 5.6 or beyond, but if we're stretching out into at least 2014 for that, even assuming your hosting provider or server admins are willing to upgrade immediately.
Yes, PHP doesn't support annotations yet, but we can rather use Doctrine Annotations. Have a look - https://www.doctrine-project.org/projects/annotations.html

Doxygen and PHP - how to parse code that is not run?

I have some PHP code that is documented with Doxygen. In this code, there are a number of hooks, which are functions that my code calls, but the functions themselves are defined by the users of this code.
I want to document the hooks, but because the functions don't exist in my code (the users define the functions, my code just calls them) there is nowhere for me to attach the Doxygen comments to - unless I define a fake function.
Is there some way I can avoid defining this fake function? If I were using C I could define the function but use #ifdefs to hide it from the compiler (but still have Doxygen see it), but I'm not sure what the equivalent is in PHP. Ideally I'd want something that wouldn't result in any additional effort on the part of the PHP parser.
Any suggestions? This is what I am trying to document, and how I have it now with the fake function:
/// This is an example hook.
/**
* Register it with $hooks['example'][] = 'your_function_name_here';
*
* #param string $dummy
* Dummy parameter.
*/
function hook_example($dummy) { }; // fake function for Doxygen
If you want other programmers to implement your hooks use OOP interfaces and abstract classes. This will sanitize your code.
As a side effect, Doxygen will be very happy to document the abstract methods.
Since PHP doesn't support #ifdef blocks, I think the only way this can be done is to take the comments and fake function declarations and put them in another .php file. Configure Doxygen to include this new file, but don't include() it anywhere in the rest of the code.
Then the fake functions will appear in the documentation, but the PHP parser will never know about them.

Extracting function declarations from a PHP file

I'm looking to create an on-site API reference for my framework and application.
Basically, say I have a class file model.class.php:
class Model extends Object {
... code here ...
// Separates results into pages.
// Returns Paginator object.
final public function paginate($perpage = 10) {
... more code here ...
}
}
and I want to be able to generate a reference that my developers can refer to quickly in order to know which functions are available to be called. They only need to see the comments directly above each function and the declaration line. Something like this (similar to a C++ header file):
// Separates results into pages.
// Returns Paginator object.
final public function paginate($perpage = 10);
I've done some research and this answer looked pretty good (using Reflection classes), however, I'm not sure how I can keep the comments in.
Any ideas?
I want to keep the current comment formatting. Myself and the people who are working on the code hate the verbosity associated with PHPDocumentor. Not to mention a comment-rewrite of the entire project would take years, so I want to preserve just the // comments in plaintext.
Why don't you just run PHPDocumenter on the code?
PHPDoc is identical to JavaDoc, and will retain all the parameters and comments in the docblock above the function.
EDIT: Since you don't want PHPDoc, I think it would probably be easiest to write a RegEx parser to do it, since Reflection won't provide you with any surrounding comments.
PHP code to get the comment:
if(preg_match("#//(.+)$#",$line,$match)>0)
{
echo "Comment is: ".$match[1];
}
this is what phpdoc is for. you comment your code a specific way, following certain rules, and when you're done you run your code through a parser. It outputs exactly what you're looking for.

Categories