PHP-Like Autoloader using Node.js - php

I'm slowly transitioning from PHP to Node.js and was trying to find something similar to composer dumpautoload. Thanks to PSR-4, it's easy to get access to any class in any file in PHP when using this command with simple use statements at the beginning of each file.
npm seems to do a great job managing packages and dependencies but having the same flexibility within your own project would avoid creating require statements that can easily break if a file changes path.
Example of what I would be looking for - 2 files in the same folder:
Some testClass.js (class file)
var testClass = {
sayHello: function () {
console.log('this is a test');
}
};
module.exports = testClass ;
Normally this is what you would put in another file index.js file:
var testClass = require('./testClass');
testClass.sayHello();
But imagine you could pre-index all your classes with some app or command (like PHP's composer dumpautoload and simply run this:
var testClass = require('testClass');
testClass.sayHello();
I couldn't find any solution that seems to achieve this.
Did I miss something?

Edit December 2020
Yarn2 did release a feature called Plug'n'Play which seems to mimic PHP's autoloader: https://yarnpkg.com/features/pnp
It is known to have issues with some packages but I have not tested it myself.
The short answer is: No
For more details, continue reading:
There are two major challenges around the current way require or import currently work:
Relative paths are hard to read and can become confusing when using files with the same name.
Developers must heavily rely on IDEs to refactor their code or to find where a file is when inside another file.
While PHP seems to have developed its own standard and is a bit in its own league, even if someone would develop an equivalent solution to achieve the same for Node.js/JavaScript, we would still need good IDE support. To get good IDE support, this type of change would either:
Need to be transparent and integrate to the way IDEs currently work.
Be a change that is driven by the community itself (either require or import changes that can support absolute paths)
There are several answers here (https://gist.github.com/branneman/8048520) and they all seem to break IDE support (I only tested with WebStorm):
Using aliases or prepending the path with variables: Breaks IDE support for autocomplete and renaming/refactoring.
Using NODE_PATH as root path: Breaks IDE support for autocomplete and renaming/refactoring.
Wrapping require to support /: Breaks IDE support when renaming/refactoring.
Creating a new custom method: Breaks IDE support for autocomplete.
Overall, given that IDE support take precedence over code readability, it looks like there is no good way to implement changes to the current dependency management using Node.js without having the community behind such change.

While not exactly like PHP, it is similar and very handy. I like this package. It is a bit older, but definitely in the right direction.
https://github.com/Specla/Autoloader
Then for database models if you are using Sequelize like I am it is pretty good.
https://github.com/boxsnake/sequelize-autoload

Related

How do I use PHP libraries without composer?

This is a really noob question... How do I use PHP libraries downloaded from GitHub? I've never experienced using libraries (even with the use of Composer). Where do I put the library folder? Are there any other steps I need to take to make the library work?
I'm trying to use PHPSpreadsheet to read and write Excel files; in their GitHub documentation, it's only about using the library in code.
I've tried searching for ways on how to use libraries without the use of Composer but they were all really specific and didn't apply to my situation. There were answers about using libraries on a server and about using libraries on Wordpress.
I just need to use the library for my thesis which will just be on one PC, no servers or anything.
A computer is a computer - PHP doesn't care whether it's a server or not. Believe it or not, every answer you saw did, indeed apply to your situation. PHP is a tool - a hammer - and you can use it to drive in nails or put dents in a fender with equal efficiency.
Put the library folder anywhere you like - literally
Then, at the top of every .php file that needs to use the library, simply add:
require '../relative/path/to/library/file.php'
or
require '/absolute/path/to/library/file.php'
It's that easy ... welcome to the wonderful world of code - where EVERY decision you make will come back to bite you on the a** ;)

how to check php function source code using eclipse

I'm curious on how certain php functions are implemented internally. e.g. array_values().
So in eclipse, I control click on the function name, which took me to a page that contain function prototype definition, but contains no internal source code.
Is there any way to see the internal implementation of php function using eclipse? (whether the function is written in php or c)
If it is not possible to see the php source code using eclipse, then does anyone have any good strategies at searching through the php source code on github?
Is there any way to see the internal implementation of php function using eclipse?
Unfortunately, no.
what is the best search strategy to search through the php source code, especially for a beginner like me, who feels very much lost in the vast amount of php source code
I'm assuming what you are really after here is a reference for native PHP functions and their input parameters and out types. In which case the official documentation is probably the best way to go about it.
Some (most?) popular IDEs such as Eclipse and Phpstorm can also give you an auto-generated phpdoc block for PHP's built-in functions that will give that information directly in your IDE.
If you are interested in the actual C implementation of most php functions, you can either navigate through the GitHub repository directly or clone it on your computer and open it in an IDE (Eclipse, CLion, etc...) and use the IDE navigation.
You can download the PHP source code from GitHub (https://github.com/php/php-src)
but the core of PHP is written in C language.
Use notepad++ to search the required details from the downloaded source code.
For example code for PHP array will be in this file :
https://github.com/php/php-src/blob/master/ext/standard/array.c
Notepad++ is the good editor with a lot of additional functionality like search string through files. (Find in files)
Hope it helps
Thanks
As an alternative, consider running OpenGrok in a Docker container. OpenGrok is an open-source and free source code indexer with advanced search mechanisms. (I am not affiliated with the project in any way)
Setting it up is easy (assuming you have Docker already installed):
# Make a directory that will contain source files for opengrok to index
mkdir ~/opengrok
# Clone the PHP source into that directory
git clone https://github.com/php/php-src.git ~/opengrok/php-src
# Start the OpenGrok container
docker run -d -v ~/opengrok:/src -p8081:8080 opengrok/docker
Now you should wait a minute or two for OpenGrok to fully index the source tree.
Open your browser
We want to search for the array_values implementation
Select the implementation in array.c
There you have it! The C implementation of array_values.

PHP code analyzer to determine classes/extensions used

Problem
I have a legacy codebase I need to analyze and determine dependencies. Particularly the dependencies on classes (internal/external) and extensions (Memcache, PDO, etc).
What I've Tried
I have reviewed the tools listed in Is there a static code analyzer for PHP files?. Unfortunately, this post is dated and most of the promising tools like phpCallGraph no longer work.
My thought was to analyze the code lexically and look for class tokens. Reviewing a list of these would at least allow me to visually determine dependencies. However finding OtherClass in the following code may be complex:
$classname = 'OtherClass';
echo $classname::doubleColon();
In the end, I doubt I'm the first to need this. I'm sure a tool or combination of tools exist to provide what I need. So I'm asking the SO community before writing this myself.
Update
Ideally this tool will analyze multiple files with complete code coverage. As such, tools like Xdebug, while great, are not solutions to this exact problem.
Instead of phpCallGraph you could use Gopal Vijayaraghavan's inclued extension which in combination with Graphviz gives you a nice looking graph of all included files for a certain execution path.
Example:
Moreover, I'd recommend Xdebug (a PHP debugger) which offers a profiler that outputs data consumable by Valgrind. Use the debugger with a compatible IDE to follow the execution path (which helped me a lot to wade thru e.g. Drupal's massive call-stack).
Combine both and you should get a fairly thourough overview.
EDIT
Searched the web and found nWire for PHP - an eclipse plugin that looks like it could be the right tool for you (30 day free trial which should be enough to give you a head start).
I think PhpCodeAnalyzer is exactly what you're looking for - https://github.com/wapmorgan/PhpCodeAnalyzer
It print list of all used external extensions in code base.

Can you use an ANT build file as a Phing build file?

I just started playing around with Phing build scripts (built with PHP). From what I have read is that Phing is based on Apache Ant (built with Java).
Both use XML build files and have similar syntax, so I am asking someone with experience, if I find an Ant build file on Github or elsewhere, can it be used in a Phing script without changing the syntax of it any? Like a drop-in XML file that would work with Ant or Phing? Or are there differences?
There are some slight differences. I would recommend taking the ant build file, and for each target, look up the target name in the phing documentation to make sure it's the same or not. I can't remember off the top of my head, but you can't just drop it in. There are also some phing only things you can do that are php related, like a phpdoc target, etc.
I were recently facing the same issue and I found some diff :
antcall would be phingcall
<if> tag only appear to be working on PHING (or with Ant-contribs library added)
<fixcrlf> tag only appear to be working on ANT
Maybe there are some others.
SOLUTION
The best solution for me was to rewrite missing tasks using adhocTask. And if it is possible, based on an existing PhingTask.
For example to make <antcall> to work, I simply extends PhingCallTask like this :
<adhoc-task name="antcall"><![CDATA[
class AntCall extends PhingCallTask {}
]]></adhoc-task>

What is a good setup for editing PHP in Emacs?

I'm going to be doing some PHP editing for my job this summer, and am looking for an effective Emacs setup for editing it. I'm already heavily invested in Emacs, so switching to another editor is not worthwhile.
Right now, I have nXhtml-mode, which provides a PHP mode with syntax highlighting (there are at least three different ones in the wild) as well as MuMaMo for editing PHP embedded in HTML. I just started using Auto-Complete and Anything for programming and general Emacs stuff, respectively.
What I'm really looking for is an effective way to get Emacs to really understand the project, beyond just highlighting. Etags looks like a good option, but it looks like the process for generating new tags is kind of arduous and manual (or at least not invisible). The nice thing about Etags is that they integrate well with Anything and Auto-Complete. Other potential options are gtags (though I'm hesitant to install non-elisp files, just for the complexity), vtags, or Semantic, which I've messed with before and seems complicated to set up, plus it doesn't look like it has support for PHP.
Another option is Imenu, but it only works for the current buffer, and I would like to be able to jump to function definitions in other files (preferably using Anything for completion of the name).
The projects I will be working on are not that big (about 30,000 lines total), so the overhead of Etags probably won't be that big of an issue, but I'd rather not use it if there is a better solution.
So what is your preferred PHP editing system?
In addition to features you are already familiar with, I suggest you the followings.
ETags
I do not use ETags, but there is a question already on SO How to programmatically create/update a TAGS file with emacs. No good answer was posted, though, but it may be a good entry point to get an idea.
Debugging
Flymake is a mode to get on the fly syntax checking. It has support for PHP as well. It hints at syntax errors immediately as you type. The Flymake version shipped with Emacs 23 contains PHP support. If you have previous version, check Sacha Chua's post on Emacs and PHP: On-the-fly syntax checking with Flymake.
Another useful package is Geben that allows you to debug your scripts interactively. For PHP, you can use XDebug. There is a detailed tutorial on how to do that, see Debug php in emacs with geben.
Documentation lookup
PHP Mode has a nice feature to lookup the function's definition in PHP's manual in your web browser (M-x php-search-documentation or C-c C-f). You can combine it with Emacs-W3M to get the relevant manual page without leaving Emacs.
web-model.el (available on web-mode.org) handles pretty well php blocks embedded in an html document. This major mode will also highlight js and css parts.
As an alternative to ETags, consider GNU Global, aka "GTags". Global is a lot smarter about finding tags tables, and is fairly fast to update. Emacs-fu has a nice post about doing this on-the-fly.
BTW, if you're using the Windows port of GNU Global with a Windows Emacs build, use the DJGPP ("DOS") version. The MinGW ("Win32") build seems to have a problem with path names.
In addition to the answer given on May 28 '09, I think I can add some packages to it which enhanced my PHP experience on Emacs.
Auto-completion
ac-php is in my opinion a good additions to Etags. All references to a tag will be found with etags, but the definition with ac-php. ac-php is also configurable to which directories should be included. For example, while developing a wordpress plugin, you can add a reference to the directory containing the wordpress files in .ac-php-conf.json (which resides in the project root) and it will auto-complete, jump to reference, etc. This package supports company-mode and auto-complete.
Here's an example configuration of ac-php:
(use-package ac-php
:ensure t
:bind (:map
php-mode-map
("M-+" . ac-php-find-symbol-at-point)
("M-]" . ac-php-location-stack-back)
("<menu> r" . ac-php-remake-tags)
("<menu> R" . ac-php-remake-tags-all)))
Another option would be to use phpactor, but the Emacs interface is at the time of writing still in alpha stage, with which I also hardly have any experience - except for the constructor completion, which works pretty well.
Error checking
In addition to syntax errors, Flycheck supports phpMessDetector and phpCodeSniffer out of the box. This enables you to have more enhanced notice/warning/error reporting based on supported coding standard and best practices.
Another package I like for static analysis is PHPStan Emacs interface, which reports potential errors in your code (including incorrect type hints).
Additional formatting
I also use phpcbf (which apparantly is archived). This package formats the buffer into the wanted coding standard.
Semantic
For anyone in the dark, Semantic is a built-in Emacs package and provides IDE like features. Here's an example how to include semantic for php-mode:
(add-hook 'php-mode-hook (lambda ()
(require 'semantic/symref/grep)
(add-to-list 'semantic-symref-filepattern-alist '(php-mode "*.php" "*.inc"))
(semantic-mode)))
Imenu
For including imenu jumping to definitions, another example configuration:
This is the sidebar for jumping to in-file methods and functions.
(use-package imenu-list
:ensure t
:config
(setq imenu-list-focus-after-activation t)
:bind (:map php-map
("<menu> \\" . imenu-list-smart-toggle)))
Example config for helm support in jumping to definitions in all project files:
(use-package imenu-anywhere
:ensure t
:after helm
:bind (:map php-map
("<menu> |" . helm-imenu-anywhere)))
Additional debugging
Besides geben, I like to use psysh, which by dropping in eval(\Psy\sh()); gives a repl on that line of code and gives access to all definitions and whatever else one would have access to (ofcourse, after requiring it in composer).
More generally handy packages
Snippets
Maybe a bit obvious for everyone already experienced with Emacs, but yasnippet is also very handy for writing your own templates. There are also packages that include a lot of predefined templates for all sorts of languages, but I write my own to keep Emacs a little less bloated than my set-up already is, it also helps me remember them more easily.
Project management
Excuse the obviousness again, but Projectile is also a very good package which by default includes git support for scoping the project.
Offline documentation
If you use Zeal for offline documentation browsing, there's also zeal-at-point. Example configuration, if you use, lets say: PHP, CodeIgniter and WordPress:
(use-package zeal-at-point
:ensure t
:bind (("<menu> z" . zeal-at-point))
:config
(add-to-list 'zeal-at-point-mode-alist '(php-mode . ("codeigniter" "wordpress" "php"))))

Categories