PHP Composer - autoload functions and constants [duplicate] - php

How can I autoload helper functions (outside of any class)? Can I specify in composer.json some kind of bootstrap file that should be loaded first?

You can autoload specific files by editing your composer.json file like this:
"autoload": {
"files": ["src/helpers.php"]
}
(thanks Kint)

After some tests, I have came to the conclusions that adding a namespace to a file that contains functions, and setting up composer to autoload this file seems to not load this function across all the files that require the autoload path.
To synthesize, this will autoload your function everywhere:
composer.json
"autoload": {
"files": [
"src/greetings.php"
]
}
src/greetings.php
<?php
if( ! function_exists('greetings') ) {
function greetings(string $firstname): string {
return "Howdy $firstname!";
}
}
?>
...
But this will not load your function in every require of autoload:
composer.json
"autoload": {
"files": [
"src/greetings.php"
]
}
src/greetings.php
<?php
namespace You;
if( ! function_exists('greetings') ) {
function greetings(string $firstname): string {
return "Howdy $firstname!";
}
}
?>
And you would call your function using use function ...; like following:
example/example-1.php
<?php
require( __DIR__ . '/../vendor/autoload.php' );
use function You\greetings;
greetings('Mark'); // "Howdy Mark!"
?>

Related

Creating composer package for Codeigniter 4

I am trying to create my first composer package for Codeigniter 4. However, I always get an error Class 'Myapp\Settings\Greet' not found. I'm totally lost.
I created a folder inside the ThirdParty folder named myapp-settings. Inside of that folder is another folder called src and composer.json.
Here's the content of that composer.json
{
"name": "myapp/settings",
"description": ".",
"license": "MIT",
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Myapp\\Settings\\": "src"
}
},
"require": {}
}
I created a test file inside the src folder named Greet.php
<?php namespace Myapp\Settings;
class Greet
{
public function hello()
{
return 'Hey, there!';
}
}
On codeigniter's App\Config\Autoload.php
public $psr4 = [
'Myapp\Settings' => APPPATH . 'ThirdParty/myapp-settings/src'
];
Then on codeigniter's default controller I called it.
<?php namespace App\Controllers;
use Myapp\Settings\Greet;
class Home extends BaseController
{
public function index()
{
$h = new Greet();
echo $h->hello();
}
//--------------------------------------------------------------------
}
Once I run it I got an error Class 'Myapp\Settings\Greet' not found. APPPATH\Controllers\Home.php at line 9. How can I fix this?
Instead of editing the codeigniter's app/Config/Autoload.php, revert it and add these lines to the project composer.json:
"repositories": [
{
"type": "path",
"url": "app/ThirdParty/myapp-settings"
}
],
// "require": {
Then run composer require myapp/settings
Since I have also stuck at this problem, a GitHub repository is created just for it. You might check and clone, watch the commits to understand the steps.

PHP Composer - php-sql-query-builder

I just figured out how to install and use PHP composer and used it to instal php-sql-query-builder to my project. The system created the vendor folder, etc. however I am having issues using classes within the package. It gives me the following error, any suggestions on how I can fix this?
Fatal error: Uncaught Error: Class 'NilPortugues\Sql\QueryBuilder\Builder\GenericBuilder' not found in D:\Documents\CadetPortal\php\lib\login.class.php on line 15
Login.class.php
require_once ("core.class.php");
require_once ("../../vendor/autoload.php");
use NilPortugues\Sql\QueryBuilder\Builder\GenericBuilder;
class LoginSystem {
private $core;
private $builder;
private $config;
function __construct(){
$this->core = new coreFunctions();
$this->builder = new GenericBuilder();
$this->config = require('core.config.php');
}
//....
}
EDIT
fncregister.php
require_once "../../vendor/autoload.php";
$LoginManager = new \ThomasSmyth\LoginSystem();
echo $LoginManager->Register($_POST["StrSurname"], $_POST["StrForename"], $_POST["StrEmail"], $_POST["StrPassword"], $_POST["DteDoB"], $_POST["StrGender"], $_POST["StrToken"]);
composer.json
{
"require": {
"nilportugues/sql-query-builder": "^1.5"
},
"autoload": {
"psr-4": {
"ThomasSmyth\\": "php/lib/"
}
}
}
Your class source files shouldn't have any require_once statements at all in them. Follow the PSR-4 spec for naming. Put your classes in a namespace to avoid collision with other classes you might include via composer. Then put one class in one file, named the same as the class. For example, the LoginSystem class should be in a file named LoginSystem.php.
namespace MyNamespace;
class LoginSystem
{
...
}
Then set your composer.json to point your namespace to your source directory:
"autoload": {
"psr-4": {
"MyNamespace\\": "src/"
}
},
Now, your main app invoker or front controller should be the only place that includes the autoloader:
require_once 'vendor/autoload.php';
$login = new \MyNamespace\LoginSystem();
...

How to use User Defined Functions in Laravel

I am new to Laravel. I want use some Own Functions. Where do Write the Function.
<?php function userrole1($roleid) {
$userrole=DB::table('roles')->where('id', '=', $roleid)->get();
?>
#foreach($userrole as $val)
<?php echo $val->role_title; ?>
#endforeach
<?php
}
?>
New Way to add Helpers
1: I created folder app/Helpers
2: In app/Providers I created new provider file HelperServiceProvider.php
3: In this file I registered all helpers classes I need
$this->app->bind('dateHelper', function()
{
return new \App\Helpers\DateHelper;
});
In config/app.php I added this new provider
'App\Providers\HelperServiceProvider',
Use This helper function dateHelper
Old Way
Create a helpers.php file in your app folder and load it up with composer:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php" // <---- ADD THIS
]
},
After adding this run composer dump-autoload command in cmd
You need to create and register your own helpers file:
http://laravel-recipes.com/recipes/50/creating-a-helpers-file
After that you'll be able to use custom helpers (functions) in your app.
Just make a function in the model class and include model and call it from the controller as pass from there to the view using variable. thats it.
In Model User(you can make any):
public function userrole1($roleid) {
$userrole=DB::table('roles')->where('id', '=', $roleid)->get();
return $userrole
}
In Controller:
use App\User
public function __construct(User $user){
$this->user_model = $user;
}
public function index(){
$userRole = $this->user_model->userrole1()
return view('admin/index', ['userRole' => $userRole]);
}

Class 'sample\question2\Hello' not found with composer and phpunit

I use composer and phpunit but the error "Class not found" is appeared.
Directory Structure:
php_sample/sample/question/
php_sample/sample/question/Hello.php
php_sample/sample/question/tests/HelloTest.php
And created composer.json
{
"require-dev": {
"phpunit/phpunit": "4.5.*"
}
}
I installed the composer like this.
$ curl -sS https://getcomposer.org/installer | php
$ ./composer.phar update
$ ./composer.phar install --dev
Hello.php is like this.
<?php
namespace sample\question;
class Hello
{
public function hello()
{
return 'Hello, world';
}
}
?>
test/HelloTest.php is like this.
<?php
namespace sample\question\tests;
use sample\question\Hello;
class HelloTest extends \PHPUnit_Framework_TestCase
{
/**
* #var Hello
*/
public $SUT;
/**
* #test
*/
public function canPrint()
{
$this->assertThat($this->SUT->hello(), $this->equalTo('Hello, world'));
}
protected function setUp()
{
$this->SUT = new Hello;
}
}
And then, I run the this script and the error is occurred.
$ vendor/bin/phpunit --bootstrap vendor/autoload.php tests/HelloTest.php
PHP Fatal error: Class 'sample\question\Hello' not found in /Users/foobar/work/php_sample/sample/question/tests/HelloTest.php on line 32
It would be great if you answer to me.
You are correctly bootstraping PHPUnit with --bootstrap vendor/autoload.php to get the files autoloaded via the Composer generated autoloaders, but
your composer.json file misses the autoload and autoload-dev sections.
{
"require-dev": {
"phpunit/phpunit": "4.5.*"
}
"autoload": {
"psr-4": {"sample\\question\\": "php_sample/sample/question/"}
}
"autoload-dev": {
"psr-4": {"sample\\question\\tests\\": "php_sample/sample/question/tests/"}
}
}
and then just re-dump/re-generate the Composer Autoloader with composer dump-autoload.
Sidenote: I'm not sure that the folder structure really works out..
Maybe its worth to change your project folder layout to:
project/src
project/tests
project/src/sample/question/
project/tests/sample/question/
then it becomes
"autoload": {
"psr-4": {"sample\\question\\": "src/"}
}
"autoload-dev": {
"psr-4": {"sample\\question\\tests\\": "tests/"}
}

Laravel 5 steam condenser

Composer.json
"autoload": {
"classmap": [
"database"
],
"files": [
"vendor/koraktor/steam-condenser/lib/steam-condenser.php"
],
"psr-4": {
"App\\": "app/"
}
},
HomeController
public function index()
{
$server = new SourceServer('80.67.11.46:27025');
try {
$server->rconAuth('abc123');
echo $server->rconExec('status');
}
catch(RCONNoAuthException $e) {
trigger_error('Could not authenticate with the game server.',
E_USER_ERROR);
}
}
I have updated the composer after adding, dump-autoload and tried all the solutions i can find with namespaces and so on.
But can't still use the steam condenser classes, any solution for this ?
The error Class 'App\Http\Controllers\SourceServer' not found denotes the fact that you're inside the App\Http\Controllers namespace and as such it will try to find the SourceServer class within that namespace. Prepend \ to your class name to call it in a global context:
$server = new \SourceServer('80.67.11.46:27025');
Or add this after the namespace declaration at the top of your controller:
use SourceServer;
And remove the class mapping from composer.json because it's not needed. You can read up more on how namespaces work in the PHP Namespaces Documentation.

Categories