eazymakaveli
eazymakaveli

Reputation: 48

PHP backend inside vuejs project folder

I created a vue/cli 3 project and its in my documents/project folder. Im running it on port 3000 with "npm run serve" command. Now, i want to have a backend folder somewhere to serve PHP files. But i want both the frontend and backend to be in the same folder structure.

Currently, my vue is in my documents folder and my php is in my xampp folder. The problem im having with this is managing 2 folders and git for the same application. Also, this causes my ajax calls from my vue projet to use a silly url such a "http://localhost:80/project/file.php". Id like to use relative paths like "backend/clients/getClient.php" that would be somewhere within my vue project.

This is what i would like:

myProject
  frontend
    my vue stuff like public and src folders
  backend
    my php files

It doesnt have to be exactly that way but the point is that now i have a single folder and git for a single project.

thank you.

Upvotes: 1

Views: 2320

Answers (1)

Jan Bijster
Jan Bijster

Reputation: 66

The way I do this is as follows:

1) I put the php files in a subfolder the public/ folder in the vue/cli project structure. That way, these files will get copied to the dist folder on building the project.

For example: I have the file /public/api/endpoint.php, this will end up in dist/api/endpoint.php.

For testing locally I now copy the php files to the xampp/htdocs dir whenever I change them. But I guess you could skip this step by setting up a xampp alias directory. (But I haven't tried this myself yet)

2) The ajax urls still differ between local development mode and production. To solve this I define a webpack plugin in my vue.config.js:

const webpack = require('webpack')

const API_URL = {
  production: JSON.stringify('https://www.project.com/api/endpoint.php'),
  development: JSON.stringify('http://localhost/project/api/endpoint.php')
}

// check environment mode
const environment =
  process.env.NODE_ENV === 'production' ? 'production' : 'development'

module.exports = {
  ...
  configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
        API_URL: API_URL[environment]
      })
    ]
  },
  ...
}

Then use this in a vue/js file like:

const apiUrl = API_URL  // eslint-disable-line

(the eslint directive is only needed If you have linting turned on with eslint, it will throw an error that API_URL is not defined.)

Upvotes: 1

Related Questions