create a custom external class in laravel 5.5 - php

I would like to create an external class in Laravel, I want to use this class in my cotroller function.
What is the best way to do that?
thanks

Create a class and define its namespace. For example:
<?php
namespace App\Services;
class MyClass
{
public function doSomething()
{
dd('It\'s working');
}
}
Run composer du command.
You'll be able to use the class in a controller with:
(new App\Services\MyClass)->doSomething();
Or with IoC:
app('App\Services\MyClass')->doSomething();
If you're using IoC, you'll also be able to inject the class into controller constructor:
use App\Services\MyClass;
protected $myClass;
public function __construct(MyClass $myclass)
{
$this->myClass = $myClass;
}
public function index()
{
$this->myClass->doSomething();
}

Used common function any file like controller,models and all blade file valid.
Please try your helpers.php file inner created.
file path like : laravel/app/helpers.php
Code
if (!function_exists('classActivePath')) {
function classActivePath($path) {
return Request::is($path) ? ' class="active"' : '';
}
}

Related

Laravel, is there a way to include codes from resource/view path into controller?

My goal is to include codes from another sources which is located in resources/views. I have tried using resource_path('views/myfiles.php') but it does nothing.
Controller
class MyController extends Controller
{
public function test(Request $request)
{
if($request->input('name') == "chair")
{
$theFilesLocation = "resources.views" . $request->input('name');
#include($theFilesLocation) //something like this
}
}
}
myfiles.php
<?php
dump("if this shows up, then the code works")
?>
Try bellow code but I think it is not a good way.
class MyController extends Controller
{
require_one(resource_path('views/myfile');
}
Or with Laravel File facade
class MyController extends Controller
{
\File::requireOnce(resource_path('views/myfile');
}
You should create a class and put your code there then call it from the controller is a better solution.
What you are looking for is a trait. This allows the easy sharing of code and functionality without having to inherit from a specific base class causing an inheritance hell.
namespace MyCode\Traits;
trait SharedCodeForThing {
public function blaTheBla() {
dump("if this shows up, then the code works");
}
}
and then in your controller
use MyCode\Traits\SharedCodeForThing ;
class MyController extends Controller
{
use SharedCodeForThing;
}
Now if you wish to just render the contents of the view which it seems you're after:
public function test(Request $request)
{
if($request->input('name') == "chair")
{
$view = view('resources.views' . $request->input('name'));
return $view->render();//or echo $view->render(); whatever you like
}
}

Symfony2: How to call PHP function from controller?

I need use a PHP function to convert numbers to letters. I create a file named: converter.php in the folder “Controller”. I need call the function named “convertir_numero_letras($number)” insert in converter.php.
I call the function “convertir_numero_letras($number)” from the following controller:
public function convertirAction()
{
$number=1234;
$this->convertir_numero_letras($number);
return $this->render('contratos/mostrar_cifra.html.twig', array('numero_convertido' => $numero_convertido));
}
But this code not work. I obtain the following
error message:
Attempted to call an undefined method named "convertir_numero_letras" of class "BackendBundle\Controller\ContratosController".
As I can fix this?
you can create a folder inside bundle like yourBundel/Helper
and create you custom class in folder like ConverHelper.php
like this :
class ConvertHelper
{
public static function numero_letras($param)
{
return 'converted value';
}
}
and then you can call in any controller and any bundle like this:
yourBundle\helper\ConverterHelper::numero_letras('someting');
don't forget to add namespace of ConverterHelper to your contoller file
example:
// file: GRF/BlogBundle/Helper/ConverterHelper.php
<?php
namespace GRF\BlogBundle\Helper;
class ConverterHelper
{
public static function toNum($param)
{
return $param;
}
}
and usage in controller:
//file controller
<?php
namespace GRF\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PostController extends Controller
{
public function indexAction()
{
return new Response(\GRF\BlogBundle\Helper\ConverterHelper::toNum(32434));
}
}

how to use an original app class in a helper class like DB or Auth on laravel 4

I create an helper class where I put some functions. It works fine till I use an other class on it:
namespace Helpers;
class Helper {
public static function helloWorld()
{
return 'Hello World';
}
public static function accessPermission($role, $filtre)
{
$jointure_session = DB::table('jointure_session')
->where('session_type',$role)
->where($filtre,1)
->get();
foreach ($jointure_session as $value_jointure_session) {
return 'Allow '.$filtre;
}
}
}
I have an error because the DB class is not found.
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Class 'Helpers\DB' not found
Any Idea?
Thank you in advance.
You have two options. Either you list the external clases in the top of your file with the world use:
<?php namespace Helpers;
use DB;
class Helper {
public static function helloWorld()
{
return DB::foo();
}
}
Either you scape the external classes with \:
<?php namespace Helpers;
class Helper {
public static function helloWorld()
{
return \DB::foo();
}
}
BTW, for simple functions you don't need to create a class. You can include your functions in a plain php file and load that file with composer. That way you avoid the namespace troubles you are having. i.e:
//File: resources/helpers.php
function helloWorld()
{
return DB::foo();
}
To load the file add this to your composer.json file
"autoload": {
"files": [
"resources/helpers.php"
],
},

how can I use custom extenstion/widget in yii2?

I use gii to generate a extension in yii2.0, here is the code
namespace ms\editor;
/**
* This is just an example.
*/
class AutoloadExample extends \yii\base\Widget
{
public function run()
{
return "Hello!";
}
}
when I want to use it in my view file,
use ms\editor\AutoloadExample;
...
<?= AutoloadExample::widget();?>
I use yii2 baisic template, and I put the "ms" folder in "vendor" folder, but it just tell me class ms\editor\AutoloadExample not found, what should I to make yii2 to find the class?is there something like "components"or "extension" folder in yii1.1?
can you help me?
Your widget should inherit the CWidget class and place the widget in components.
public class AutoloadExample extends CWidget
{
public function run() { }
}
You can then run the widget in your view like this;
$this->widget('application.components.AutoloadExample', array('your variables'));
Would you try one such?
for example create a file in "app/frontend/widgets/"
File Name : Deneme.php
<?php
namespace frontend\widgets;
class Deneme
{
static function yazdir () {
echo 'asd';
}
}
To use;
use frontend\widgets\Deneme;
Deneme::yazdir();

Issue with Facade and injected dependency in Laravel 4

I am having an issue getting a Facade to work properly with a dependency injected into the underlying class.
I have a class called 'Listing'. It has one dependency called 'AdvertRepository' which is an interface and a class called EloquentAdvert which implements the interface. The code for these three classes is here:
// PlaneSaleing\Providers\Listing.php
<?php namespace PlaneSaleing\Providers;
use PlaneSaleing\Repositories\Advert\AdvertRepository;
class Listing {
protected $advert;
public function __construct (AdvertRepository $advert_repository) {
$this->advert = $advert_repository;
}
public function test() {
$this->advert->test();
}
public function test2() {
echo "this has worked";
}
}
// PlaneSaleing\Repositories\Advert\AdvertRepository.php
<?php namespace PlaneSaleing\Repositories\Advert;
interface AdvertRepository {
public function test();
}
// PlaneSaleing\Repositories\Advert\EloquentAdvert.php;
<?php namespace PlaneSaleing\Repositories\Advert;
class EloquentAdvert implements AdvertRepository {
public function test() {
echo 'this has worked';
}
}
I have then created a service provider called ListingServiceProvider.php, which has the following code:
// PlaneSaleing/Providers/ListingServiceProvider.php
<?php namespace PlaneSaleing\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;
class ListingServiceProvider extends ServiceProvider {
public function register() {
App::bind('PlaneSaleing\Repositories\Advert\AdvertRepository', 'PlaneSaleing\Repositories\Advert\EloquentAdvert');
}
}
I also added this to the ServiceProviders array in app.php
Now, if I inject Listing as a dependency into a controller and call the test method (as shown below) Laravel correctly detects the dependency, instantiates EloquentAdvert via its binding and displays 'this has worked'.
// Controllers/TestController.php
use PlaneSaleing\Providers\Listing;
class TestController extends BaseController {
protected $listing;
public function __construct(Listing $listing) {
$this->listing = $listing;
}
public function test1() {
$this->listing->test();
}
}
Now, I then created a facade for Listing. I added a new facade as follows and added an alias in app.php:
// PlaneSaleing\Providers\ListingFacade.php
<?php namespace PlaneSaleing\Providers;
use Illuminate\Support\Facades\Facade;
class ListingFacade extends Facade {
protected static function getFacadeAccessor() {
return 'Listing';
}
}
I also added the following new lines to ListingServiceProvider.php:
<?php namespace PlaneSaleing\Providers;
use PlaneSaleing\Repositories\Advert\AdvertRepository;
use PlaneSaleing\Repositories\Advert\EloquentAdvert;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;
class ListingServiceProvider extends ServiceProvider {
public function register() {
App::bind('PlaneSaleing\Repositories\Advert\AdvertRepository', 'PlaneSaleing\Repositories\Advert\EloquentAdvert');
// New lines...
$this->app['Listing'] = $this->app->share(function() {
return new Listing(new AdvertRepository);
});
}
}
NOW...if I call Listing::test(), I get the following error: Cannot instantiate interface PlaneSaleing\Repositories\Advert\AdvertRepository.
If I call Listing::test2() , I get 'this has worked' so it seems the Facade is working correctly.
It seems that when accessing Listing via its Facade the binding between AdvertRepository and EloquentAdvert doesnt work. I have looked at my code in the ServiceProvider thinking it was the issue, but I cant figure it out.
Both the Facade and binding work when tested individually but not when both are used at the same time.
Any ideas???
OK, So I have figured it out...For those who run into a similar problem...
The offending statement was in ListingServiceProvider.php which read:
$this->app['Listing'] = $this->app->share(function() {
return new Listing(new AdvertRepository);
});
The error is the new AdvertRepository statement. The reason being is that, we are telling php to directly instantiate the interface 'AdvertRepository'. Instead, we need to tell Laravel to instantiate the appropriate implementation of the 'AdvertRepository' interface. To do that, we use App::make('AdvertRepository'). That way, Laravel uses the binding previously declared to instantiate the correct implementation.
If your constructor is not being inject with a class, you must tell Laravel what class will be used when it needs to instantiate a particular interface:
Put this in your filters or bindings file:
App::bind('PlaneSaleing\Repositories\Advert\AdvertRepository', function()
{
return new PlaneSaleing\Repositories\Advert\EloquentAdvert;
});

Categories