0

I want to create a directory for utils in Laravel 8. I have this but it doesn't work:

app/Utils/DateTime.php:

<?php

namespace App\Utils\DateTime;

const ISO8601_DATE_FORMAT = "Y-m-d\TH:i:s.uP";  

function parseISO8601(string $time): \DateTime {
    if ($time.endsWith("Z")) {
        $time = $time.str_replace($time, "Z", "+00:00");
    }
    return \DateTime::createFromFormat(ISO8601_DATE_FORMAT, $time);
}

app/Http/Controllers/SearchController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;

use function App\Utils\DateTime\parseISO8601 as parseISO8601;

class SearchController extends Controller
{
    public function run(Request $request)
    {
        parseISO8601("2021-10-03T10:00:45.145126+01:00");
    }
}

But I get an error:

Call to undefined function App\Utils\DateTime\parseISO8601()

What am I missing? It seems that it can't autoload DateTime for some reason. Do I need to manually configure an extra path somewhere in Laravel?

jbrown
  • 7,518
  • 16
  • 69
  • 117
  • You don't need `as parseISO8601` since you're using the same name. You only need that if you're creating an alias (renaming the function because of name collisions) – M. Eriksson Sep 29 '21 at 07:53
  • What about https://stackoverflow.com/questions/24171078/composer-psr-how-to-autoload-functions? – Nico Haase Sep 29 '21 at 07:57

1 Answers1

0

I changed it to a class and restarted PHP. It then gave me an error:

Class App\Utils\DateTime\DateTime located in ./app/Utils/DateTime.php does not comply with psr-4 autoloading standard. Skipping. which is explained here

I had incorrectly specified the namespace as App\Utils\DateTime even though the file was called DateTime.php. I just needed to change the namespace to App\Utils.

jbrown
  • 7,518
  • 16
  • 69
  • 117