I am trying to get the Bronto api PHP lib to work with composers autoload. But no go. What is missing?
Composer.json:
{
"require": {
"slim/slim": "2.4.*",
"bronto/bronto-api-php-client": "dev-master"
},
"minimum-stability": "dev"
}
index.php
<?php
require '../vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/', function () {
$bronto = new \Bronto_Api();
$bronto->setToken($token); // Or pass $token to the constructor of Bronto_Api
$bronto->login(); // Only needs to be called once
});
$app->run();
Slim's framework loads fine. I just keep getting a 'Fatal error: Class 'Bronto_Api' not found in /app/location/'.
Any ideas on what could be going on?
This is 3 years after the original question was asked but I had the same problem trying to add the package to a Laravel project I was working on. I resolved it by adding the following to my composer.json (the one belonging to my project).
"autoload": {
"psr-0": {
"Bronto_": "./vendor/bronto/bronto-api-php-client/Symfony/Component/Console/src/"
}
}
It feels a little dirty but works OK.
Related
Please, don't talk to technical in the answers:-D I am not a hardcore programmer.
What is a good way to store certain functions in Laravel? I have functions that apply on a "post" only or "media" only, like getAttributeList or getComponents. I say "Post" and "Media" because both have their own controller, model and views. It feels wrong to put it in the model because that should be database stuff right? And traits are more for recurring functions all over the place, right? So, right now I have one big file called Helpers.php. And uh, it is getting large... should I simply separate it in PostHelpers.php, MediaHelpers.php etc? Or is there a more elegant way in Laravel to do it?
It is quite simple : Just check your composer.json file at root directory of ur app. and under autoload section add :
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": ["app/helper.php"],
"classmap": [
"database/seeds",
"database/factories"
]
"files": ["app/helper.php"], This is the line you need to add in ur composer file and provide the path to file .
In my case i have created a file helper.php in App directory where i keep all my functions .
after this run this command :
composer dump-autoload
Now u can access your functions anywhere.
In your composer json file check this snippet
"autoload": {
"files": [
"app/Helpers/global_helper.php"
],
As you see I have auto loaded 1 single file called global_helper.php in a folder called Helpers Now in this file I have a function called loadHelper(...$files)
What this function does is
if (!function_exists('loadHelper')) {
function loadHelper(...$file_names)
{
foreach ($file_names as $file) {
include_once __DIR__ . '/' . $file . '_helper.php';
}
}
}
You can pass your file name as array or string and it will include those files into your Controller constructor
So In my Controller whenever I want some helper function I create a saperate helper file for that controller then in constructor i ust include it.
I am not sure if there is any better solution but so far this is how I am making all my projects .
I hope this will help you ;)
Can you help me? I'm facing a strange issue.
First, I'm downloading this https://github.com/tuupola/slim-jwt-auth using composer:
composer require tuupola/slim-jwt-auth
After that, I created a php file called: teste.php:
require 'vendor/autoload.php';
$app = new Slim\App;
$app->add(new \Slim\Middleware\JwtAuthentication([
"secret" => "teste",
"callback" => function ($options) use ($app) {
$app->jwt = $options["decoded"];
}
]));
$app->get("/user", function () {
print_r($app->jwt);
});
$app->run();
And now, I'm getting this error:
PHP message: PHP Fatal error: Uncaught Error: Class 'Slim\App' not found
This does not make sense, since I used the composer correctly
How can I solve that? I spent many hours trying fix this by myself and I failed. Thank you!
First of all, you need to actually add the Slim framework to your Composer package. You can do this by running:
composer require slim/slim
Regarding your other problem, the constructor you're using for the middleware is incorrect. It should be: new Tuupola\Middleware\JwtAuthentication.
Your complete code should be as follows:
require 'vendor/autoload.php';
$app = new Slim\App;
$app->add(new Tuupola\Middleware\JwtAuthentication([
"secret" => "teste",
"callback" => function ($options) use ($app) {
$app->jwt = $options["decoded"];
}
]));
$app->get("/user", function () {
print_r($app->jwt);
});
$app->run();
I am trying to get a minimum Symfony routing system together to run on the side of my Laravel install for the incoming APIs to be outside the full Laravel install. I noticed that our normal Laravel system includes 575 files to render / load and it just is too slow to handle the incoming workload. More details here: https://serverfault.com/questions/959018/apache-tuning-for-512gb-ram
To put it together I made up a new composer file named minvendor.json with the following:
{
"config": {
"vendor-dir": "minvendor"
},
"require": {
"symfony/routing": "^4.2",
"symfony/http-foundation": "^4.2",
"symfony/yaml": "^4.2",
"symfony/config": "^4.2"
}
}
Since there is already a composer.json file, you have to use a different command to load the minvendor.json file.
env COMPOSER=minvendor.json composer install
I then put the following into the .htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^api api.php [L]
After that I made the api.php file with the following
<?PHP
require __DIR__.'/../minvendor/autoload.php';
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
$fileLocator = new FileLocator([__DIR__]);
$loader = new YamlFileLoader($fileLocator);
$routes = $loader->load('routes.yaml');
class LuckyController
{
public function number()
{
$number = random_int(0, 100);
return new Response(
'<html><body>Lucky number: '.$number.'</body></html>'
);
}
}
and in the routes.yaml file:
route1:
path: api/foo
controller: LuckyController::number
methods: GET|POST
Using the php function print_r(get_included_files()) I can see I am only using 20 include files for this new way, so much better, but I don't get anything returned to the browser when I go to the site: http://www.myserver.org/api/foo
I tried a couple other ways such as:
$foo_route = new Route('/api/foo', array('App\Http\Controllers\Api\V2\LuckyController' => 'number') );
Nothing I do seems to get Symfony to access the functions and return the results to the browser. What am I missing in the process?
Dbrumann had a much better link than I did. I had been going through the regular documentation section here: https://symfony.com/doc/current/routing.html instead of the Build Your Own Framework section: https://symfony.com/doc/current/create_framework/routing.html
Before I got his response I tried a different routing library Macaw (https://github.com/noahbuscher/macaw) which ended up being pretty simple and used much fewer include files.
In addition to the routing, I needed an autoloader since the controller files were outside the public directory, I chose robot-loader, so now my minvendor.json file looks like this:
{
"config": {
"vendor-dir": "minvendor"
},
"require": {
"noahbuscher/macaw": "dev-master",
"nette/robot-loader": "dev-master"
}
}
and a full working example page would look like this:
<?PHP
require __DIR__.'/../minvendor/autoload.php';
use \NoahBuscher\Macaw\Macaw;
$loader = new Nette\Loaders\RobotLoader;
// Add directories for RobotLoader to index
$loader->addDirectory(__DIR__ . '/../app/Http/Controllers/Api/V2');
// And set caching to the 'temp' directory
$loader->setTempDirectory(__DIR__ . '/temp');
$loader->register(); // Run the RobotLoader
//just a couple ways you can define routes
Macaw::get('/api/foo', function() {
echo 'Hello world!';
});
Macaw::post('/api/bar', 'App\Http\Controllers\Api\V2\Controller#accounting');
Macaw::dispatch();
I have some php lines which will be used very often in my application. So I would like to build a function and call it every where in my app. My function could be :
static function array_matiere($id_ecole) {
return $something;
}
I tried to put this code in a controller and then call it like that :
$liste_matieres = MatieresController::array_matieres(Session::get('id_ecole'));
It works, but where to put this kind of function ? in the controller ? in a method file ? what is the best practice ?
Thanks for your responses.
Dominique
There are multiple ways to implement this. look here
Method 1 This method is highly suggested by Laravel Expert ( JeffreyWay)
If your helper functions are similar to the way laravel 5 ones work, i.e Illuminate/Support/helpers.php you could just create a helpers.php and have composer do the autoloading for you.
Edit your composer.json file and add the file to the autoloading key. In my example my app is called Tasky so just add the files key and reference helpers.php.
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"Tasky\\": "app/"
},
"files": [
"app/Support/helpers.php"
]
},
That way you just create your file inside app/Support/helpers.php and all your common function based view helpers or other helpers can go here. If you take the class based approach then the above is great.
Also then remember to just run the following once.
$ composer dumpautoload
Source
Method 2
Please Follow the link and read answer & Its comments
Whenever u need to include a piece of code providing some functionality through out your application then the best way in Laravel is to make Service class inside app/Services and then you can use that class anywhere in your application using
use App\Services\YourServiceName;
According to the Silex documentation:
Symfony provides a Twig bridge that provides additional integration between some Symfony2 components and Twig. Add it as a dependency to your composer.json file.
I include the following in my composer.json file:
{
"require": {
"silex/silex": "1.*",
"twig/twig": ">=1.8,<2.0-dev",
"symfony/twig-bridge": "2.3.*"
}
}
I register the TwigServiceProvider() like so:
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__ . '/views'
));
I'm attempting to use the twig path() method like so:
Log out
The error I get is as follows:
Twig_Error_Syntax: The function "path" does not exist
Why am I getting this error?
I have tried switching around versions to check if it is a version issue
One google groups comment suggested 'registering' the twig bridge provider, but this doesn't exist
I don't want to have to use: app.url_generator.generate in all my templates instead
A temporary solution I have found:
Ensure The UrlGeneratorServiceProvider() is registered:
$app->register(new UrlGeneratorServiceProvider());
Create a new function for twig for path():
$app['twig']->addFunction(new \Twig_SimpleFunction('path', function($url) use ($app) {
return $app['url_generator']->generate($url);
}));
I shouldn't have to do this!! How can I get this working properly?
Hopefully this will help future viewers as many have posted this question without a solid answer, so here is one.
It is literally that you need UrlGeneratorServiceProvider() registered
$app->register(new UrlGeneratorServiceProvider());
Also, as umpirsky mentions in the comments, you need symfony/twig-bridge installed via composer.
You do not need to add your own function. You need both the TwigServiceProvider() and the UrlGeneratorServiceProvider() registered before loading your twig template. This isn't easily apparent from the documentation.
I too had to create a new function for twig for path(), but I improved it a bit to handle a variable number of arguments to allow passing arrays in the twig template:
$app['twig']->addFunction(new \Twig_SimpleFunction('path', function(...$url) use ($app) {
return call_user_func_array(array($app['url_generator'], 'generate'), $url);
}));
Four easy steps.
Create the loader
Create the twig object.
Create you custom function
Add to the Twig object.
use Twig\Environment;
use Twig\TwigFunction;
use Twig\Loader\FilesystemLoader;
$loader = new FilesystemLoader('/twig/templates');
$twig = new Environment($loader, []);
$function = new TwigFunction('url', function () { return 'MyURL'; });
$twig -> addFunction($function);