2

I have a file that calculates something, lets say tax. Tax.php, this is inside some folder, lets say /MyCalculations/Taxes/Tax.php.

Now I want this file to be accessible inside my controller, How do I access this file, or how do I access those calculations inside this file?

Sample code of Tax.php:

<?php namespace MyCalculations/Taxes;

  class Taxes extends Enginge {
    //some calculations here
  }
?>

I'm using laravel. Thanks

2 Answers 2

2

You could start by creating a namespace for your application, and place a folder in your app directory, perhaps app/Projectname. Then you could place your calculations namespace there there. Then autoload everything in your project by adding

"autoload": {
    "classmap": [
        "..."
    ],
    "psr-0": {
        "Projectname": "app/"
    }
},

to your composer.json file and then do a dump-autoload. Then you could use dependency injection in your controller, like so:

use Projectname\MyCalculations\Taxes\Tax;

class TaxController extends BaseController {

    protected $tax;

    public function __construct(Tax $tax)
    {
        $this->tax = $tax;
    }

    public function getTaxValue()
    {
        $value = Input::get('value');

        return $this->tax->getAwesome($value);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

@nielisano Sir, if I'm using blade to display those calculations, can also put use Projectname\MyCalculations\Taxes\Tax; inside the myview.blade.php and access those data or i should do it via controller?
You could make a facade for that, so you could do Tax::getAwesome($value), but i'd much rather do that in a presenter before passing the variable to a view. Check out github.com/ShawnMcCool/laravel-auto-presenter and read about facades in the Laravel Docs.
0

Edit your composer.json file and add the 'files' section to it to it:

"autoload": {
    ...

    "files": [
        "app/MyCalculations/Taxes/Tax.php"
    ]
},

Then you just have to execute:

composer dump-autoload

And use them everywhere.

If you are on PHP 5.5, you also can use traits:

<?php namespace MyCalculations/Taxes;

  trait TaxesTraits  {

     function calculateX()
     {

     }

  }

  class Taxes extends Enginge {
     use TaxesTraits;

     public function calculate()
     {
        $x = $this->calculateX();
     }
  }

1 Comment

@Belmark Caday : If you plan to have multiple custom classes I would recommend setting up a global namespace and a new libraries directory for your custom classes. This is a good post to read on the subject - I have used similar structures in the past and have been pleased with the results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.